Last active
November 18, 2018 22:05
-
-
Save lylek/24caa515d757a89b9a7ce369fa4df390 to your computer and use it in GitHub Desktop.
Logic and Proof Exercise 17.19 Haskell solution
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
-- 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