Skip to content

Instantly share code, notes, and snippets.

@line-o
Forked from joewiz/fib-exist.xq
Last active October 12, 2020 14:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save line-o/56022d605b466812013ab72946e3d79b to your computer and use it in GitHub Desktop.
Save line-o/56022d605b466812013ab72946e3d79b to your computer and use it in GitHub Desktop.
XQuery Fibonacci reducer function, with timing, for eXist-db
xquery version "3.1";
(: adapted from https://stackoverflow.com/a/4936099 :)
declare function local:fib-reducer ($r, $n) { $r[1] + $r[2], $r[1] };
declare function local:fib($n as xs:integer) {
fold-left((1 to $n), (0,1), local:fib-reducer#2)[1]
};
let $results :=
for $n in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 30, 40, 50, 60, 70, 80, 90)
let $start-time := util:system-time()
let $fib := local:fib($n)
return
$n || " = " || $fib || ", " || (util:system-time() - $start-time) div xs:dayTimeDuration("PT1S") || "s"
return
string-join($results, "
")
1 = 1, 0s
2 = 1, 0s
3 = 2, 0s
4 = 3, 0.001s
5 = 5, 0s
6 = 8, 0s
7 = 13, 0s
8 = 21, 0s
9 = 34, 0s
10 = 55, 0s
15 = 610, 0s
20 = 6765, 0.001s
30 = 832040, 0s
40 = 102334155, 0s
50 = 12586269025, 0s
60 = 1548008755920, 0.001s
70 = 190392490709135, 0s
80 = 23416728348467685, 0s
90 = 2880067194370816120, 0s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment