Skip to content

Instantly share code, notes, and snippets.

@onlyleft
Created August 22, 2014 10:22
Show Gist options
  • Select an option

  • Save onlyleft/5f1a7d6327f4139f519c to your computer and use it in GitHub Desktop.

Select an option

Save onlyleft/5f1a7d6327f4139f519c to your computer and use it in GitHub Desktop.
Learning Haskell with Project Euler - Second attempt at Problem 2 (Fibonacci Sequence Sum with Limit)
-- Get the fibonacci sequence up to a limit
fml :: Int -> [Int] -> [Int]
fml limit seed
| null seed = fml limit [1, 1]
| nextNumber < limit = fml limit (seed ++ [nextNumber])
| otherwise = seed
where nextNumber = ((last (init seed)) + (last seed))
-- Implementation to retrieve a specific fibonacci number
fm :: Int -> [Int] -> Int
fm 0 _ = 0
fm 1 _ = 1
fm fibSeq seed
| null seed = fm fibSeq [1, 1]
| length seed > fibSeq = seed !! fibSeq
| otherwise = fm fibSeq (seed ++ [nextNumber])
where nextNumber = ((last (init seed)) + (last seed))
main = do
print (sum (fml 4000000 [])) -- Based on https://projecteuler.net/problem=2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment