Skip to content

Instantly share code, notes, and snippets.

@lylek
Last active November 18, 2018 22:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lylek/24caa515d757a89b9a7ce369fa4df390 to your computer and use it in GitHub Desktop.
Save lylek/24caa515d757a89b9a7ce369fa4df390 to your computer and use it in GitHub Desktop.
Logic and Proof Exercise 17.19 Haskell solution
-- Logic and Proof Exercise 17.19
-- Finds an increasing list of Fibonacci numbers that sum to the given natural number.
-- The algorithm is linear in the input number, and tail recursive.
main = mapM_ print $ map fibsSummingTo [0..100]
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
fibsSummingTo :: Integer -> [Integer]
fibsSummingTo n = loop n ltFibs []
where
ltFibs = reverse $ takeWhile (<= n) fibs
loop :: Integer -> [Integer] -> [Integer] -> [Integer]
loop targ remFibs acc =
let hd : tl = remFibs in
case compare hd targ of
EQ -> hd : acc
GT -> loop targ tl acc
LT -> loop (targ - hd) tl (hd : acc)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment