Skip to content

Instantly share code, notes, and snippets.

@MarkArts
Created April 19, 2016 13:08
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 MarkArts/a9eddcac752ffabe8dea59c914388e8b to your computer and use it in GitHub Desktop.
Save MarkArts/a9eddcac752ffabe8dea59c914388e8b to your computer and use it in GitHub Desktop.
Some Haskell fun with Fibonacci and the tower of Hanoi
main = do
putStrLn . show . last . fib' $ 30000
putStrLn . show $ move 4 1 2 3
fib :: (Eq a, Num a) => a -> a
fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n-2)
fib' :: (Eq a, Num a) => a -> [a]
fib' n = reverse $ grow n [1, 0]
where grow n xs = case n of 0 -> xs
_ -> grow (n-1) $ [first xs + second xs] ++ xs
first = head
second = flip (!!) 1
fibs :: [Integer]
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
move :: Integer -> Integer -> Integer -> Integer -> [String]
move = move' []
where move' xs x from to spare | x <= 1 = ["Move from: " ++ (show from) ++ " to: " ++ (show to)]
| otherwise = xs ++
move' xs (x-1) from spare to ++
move' xs 1 from to spare ++
move' xs (x-1) spare to from
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment