haskell.hs 512 B

1234567891011121314151617181920
  1. -- Type annotation (optional)
  2. fib :: Int -> Integer
  3. -- With self-referencing data
  4. fib n = fibs !! n
  5. where fibs = 0 : scanl (+) 1 fibs
  6. -- 0,1,1,2,3,5,...
  7. -- Same, coded directly
  8. fib n = fibs !! n
  9. where fibs = 0 : 1 : next fibs
  10. next (a : t@(b:_)) = (a+b) : next t
  11. -- Similar idea, using zipWith
  12. fib n = fibs !! n
  13. where fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
  14. -- Using a generator function
  15. fib n = fibs (0,1) !! n
  16. where fibs (a,b) = a : fibs (b,a+b)