Created
July 23, 2015 17:23
-
-
Save amar47shah/4f3b786e0b6237d28377 to your computer and use it in GitHub Desktop.
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
-- Tail-recursive Fibonacci | |
fib n = go n (0, 1) | |
where | |
-- (x, y) are the last two calculated Fibonacci numbers | |
-- n is how many more Fibonacci steps to take | |
-- calling `go` is the final step in evaluating `go (n - 1) (y, x + y)` | |
go n (x, _) | n < 1 = x | |
go n (x, y) = go (n - 1) (y, x + y) | |
-- Naive implementation | |
-- Note that the second line can be written | |
-- fib' n = (+) (fib' (n - 1)) (fib' (n - 2)) | |
-- | |
-- not tail-recursive since the results of calling fib' | |
-- are needed before doing (+) | |
fib' n | n < 1 = 0 | |
fib' n = fib' (n - 1) + fib' (n - 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment