Last active
August 29, 2015 14:18
-
-
Save sefufuller/37a90f38cb5ecfd96531 to your computer and use it in GitHub Desktop.
Fibonacci numbers
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
-- Type annotation (optional) | |
fib :: Int -> Integer | |
-- With self-referencing data | |
fib n = fibs !! n | |
where fibs = 0 : scanl (+) 1 fibs | |
-- 0,1,1,2,3,5,... | |
-- Same, coded directly | |
fib n = fibs !! n | |
where fibs = 0 : 1 : next fibs | |
next (a : t@(b:_)) = (a+b) : next t | |
-- Similar idea, using zipWith | |
fib n = fibs !! n | |
where fibs = 0 : 1 : zipWith (+) fibs (tail fibs) | |
-- Using a generator function | |
fib n = fibs (0,1) !! n | |
where fibs (a,b) = a : fibs (b,a+b) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment