Created
July 30, 2019 21:30
-
-
Save seisvelas/d60f5f2caf232dceede0326169014418 to your computer and use it in GitHub Desktop.
Recursive Fibonacci sequence up to nth number in SQL
This file contains 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
WITH RECURSIVE fib (a, b, n) AS ( | |
SELECT 0, 1, 1 | |
UNION ALL | |
SELECT b, a+b, n+1 FROM fib | |
) | |
SELECT a FROM fib WHERE n<=8; |
Here is another implementation I made today in plpgsql, tail recursion:
CREATE OR REPLACE FUNCTION fibTailRecursive(n INTEGER, prevFib INTEGER DEFAULT 0, fib INTEGER DEFAULT 1)
RETURNS INTEGER AS $$
BEGIN
IF (n = 0) THEN
RETURN prevFib;
END IF;
RETURN fibTailRecursive(n - 1, fib, prevFib + fib);
END;
$$ LANGUAGE plpgsql;
When I was coding my solution in TablePlus it DID notice that it's outer scope only cares about n=8
. That's why it ran forever for you but not for me. TablePlus is smart about that stuff. But I see what you mean, haha.
Recursion has sort of come under the dominion of functional programming, and this is a clearly non-functional approach to recursion. Do you have Hangouts? I'd love to chat more. It warms my heart to see people pursuing curiosity and intellectual gratification.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fair enough, all functions drill down to some clever
JMP
instructions. What boggles my mind is that the "body" of the recursive CTE where theUNION ALL
is iterating the result does not care about it's outer scope wanting to have justn<=8
results. I feel like the base case is missing. There is no returning of a value, it is iterating till infinity.Don't get me wrong I'm convinced this is a recursive pattern and I enjoyed reading your comment!