Skip to content

Instantly share code, notes, and snippets.

@SnipyJulmy
Created October 26, 2018 10:21
Show Gist options
  • Save SnipyJulmy/6c119fa387f2b081d05a999a77219586 to your computer and use it in GitHub Desktop.
Save SnipyJulmy/6c119fa387f2b081d05a999a77219586 to your computer and use it in GitHub Desktop.
Fibonacci in CPS style
fib :: Int -> Int
fib n = inner n (\x -> x) where -- setup the identity function for the base cases
inner :: Int -> (Int -> Int) -> Int
inner 0 cont = cont 0 -- base case for fibonacci, first two number are known
inner 1 cont = cont 1
-- 1st : function is tail recursive, so we call inner no matter what
-- we have to progress to the base case, so we decrement n
-- since fib n = fib (n-1) + fib (n-2), we already have the call to (n-1)
-- and have to add the call to (n-2)
-- the call to inner (n-2) also need a continuation function, which is juste x + y since both (n-1) and (n-2) have to be summed
inner n cont = inner (n-1) (\x -> inner (n-2) (\y -> x + y))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment