Haskell and the Tower of Hanoi

300px-Tower_of_Hanoi_4

https://en.wikipedia.org/wiki/Tower_of_Hanoi

hanoi :: Integer -> String -> String -> String -> [(String, String)]
hanoi 0 _ _ _ = []
hanoi n a b c = hanoi (n-1) a c b ++ [(a, b)] ++ hanoi (n-1) c b a

hanoiIO n = mapM_ f $ hanoi n "Pole 1" "Pole 3" "Pole 2" where
  f (x,y) = putStrLn $ "Move from " ++ show x ++ " to " ++ show y

main = do
  hanoiIO 3
Move from "Pole 1" to "Pole 3"
Move from "Pole 1" to "Pole 2"
Move from "Pole 3" to "Pole 2"
Move from "Pole 1" to "Pole 3"
Move from "Pole 2" to "Pole 1"
Move from "Pole 2" to "Pole 3"
Move from "Pole 1" to "Pole 3"

Leave a Reply

Your email address will not be published. Required fields are marked *