Towers of Hanoi in Haskell


/ Published in: Haskell
Save to your folder(s)



Copy this code and paste it in your HTML
  1. --Haskell Towers of Hanoi
  2. -- ... because you know you want to...
  3.  
  4. import System.Environment
  5.  
  6. -- you are moving from a to b using c as an intermediate
  7. hanoi :: Integer -> a -> a -> a -> [(a,a)]
  8. hanoi 0 _ _ _ = []
  9. hanoi n a b c = hanoi (n - 1) a c b ++ [(a,b)] ++ hanoi (n - 1) c b a
  10.  
  11. hanoiIO :: Integer -> IO ()
  12. hanoiIO n = mapM_ f $ hanoi n "one" "two" "three" where
  13. f (x,y) = putStrLn $ "Move " ++ show x ++ " to " ++ show y
  14.  
  15. -- for some reason this doesn't work in GHCi. Use main' in GHCi
  16. main :: IO ()
  17. main = do
  18. args <- getArgs
  19. hanoiIO $ read (args !! 0)
  20.  
  21. main' = hanoiIO 3

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.