Towers of Hanoi: Difference between revisions

m
m (→‎{{header|E}}: lang (lang e, even though there's no e in geshi still))
Line 349:
Most of the programs on this page use an imperative approach (i.e., print out movements as side effects during program execution). Haskell favors a purely functional approach, where you would for example return a (lazy) list of movements from a to b via c:
 
<lang haskell> hanoi :: Integer -> a -> a -> a -> [(a, a)]
hanoi 0 _ _ _ = []
hanoi n a b c = hanoi (n-1) a c b ++ [(a,b)] ++ hanoi (n-1) c b a</lang>
 
One can use this function to produce output, just like the other programs:
 
<lang haskell> hanoiIO n = mapM_ f $ hanoi n 1 2 3 where
f (x,y) = putStrLn $ "Move " ++ show x ++ " to " ++ show y</lang>
 
Or, instead one can of course also program imperatively, using the IO monad directly:
 
<lang haskell> hanoiM :: Integer -> IO ()
hanoiM n = hanoiM' n 1 2 3 where
hanoiM' 0 _ _ _ = return ()
Line 366:
hanoiM' (n-1) a c b
putStrLn $ "Move " ++ show a ++ " to " ++ show b
hanoiM' (n-1) c b a</lang>
 
=={{header|Io}}==