Last active
December 31, 2015 14:08
-
-
Save CliffordAnderson/7997843 to your computer and use it in GitHub Desktop.
Fibonacci sequence in XQuery
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| xquery version "3.0"; | |
| (: Fibonacci Sequence :) | |
| declare function local:fibo-numbers($num1 as xs:integer, $num2 as xs:integer, $limit as xs:integer) as xs:integer* { | |
| if ($limit > 0) then ($num1, local:fibo-numbers($num2, $num1 + $num2, $limit -1)) | |
| else $num1 | |
| }; | |
| declare function local:fibo-sequence($limit as xs:integer) as xs:integer* { | |
| local:fibo-numbers(0, 1, $limit) | |
| }; | |
| local:fibo-sequence(15) |
Author
Author
A tail-recursive version is blazingly fast because it does not need to keep intermediate values on the stack. Notice how close this tail-recursive version is to the initial algorithm for generating the sequence above:
(: Fibonacci Number :)
declare function local:fibo-sequence($num1 as xs:integer, $num2 as xs:integer, $limit as xs:integer) as xs:integer* {
if ($limit > 0) then local:fibo-sequence($num2, $num1 + $num2, $limit -1)
else $num1
};
declare function local:fibo-number($limit as xs:integer) as xs:integer* {
local:fibo-sequence(0, 1, $limit)
};
local:fibo-number(200)
Author
See this XQuery Wikibook for more information about the Fibonacci algorithm in XQuery as well as how to time the difference between implementations.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A classically recursive algorithm for computing Fibonacci numbers is even simpler:
However, the depth of the recursion required for calculating numbers above twenty-five slows down the computation dramatically.