Skip to content

Instantly share code, notes, and snippets.

@seisvelas
Created July 30, 2019 21:30
Show Gist options
  • Save seisvelas/d60f5f2caf232dceede0326169014418 to your computer and use it in GitHub Desktop.
Save seisvelas/d60f5f2caf232dceede0326169014418 to your computer and use it in GitHub Desktop.
Recursive Fibonacci sequence up to nth number in SQL
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;
@A1rPun
Copy link

A1rPun commented Sep 13, 2019

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;

@seisvelas
Copy link
Author

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