StyleInCode

RSS

 

Tower of Hanoi

A solution calculating the moves needed to solve the Tower of Hanoi puzzle.

Solution

-- tower_of_hanoi.hs --

-- usage: ghci tower_of_hanoi.hs
--        hanoi discs "peg1" "peg2" "peg3"

type Peg = String
type Move = (Peg, Peg)

hanoi :: Integer -> Peg -> Peg -> Peg -> [Move]
hanoi 0 _ _ _ = []
hanoi 1 x y _ = [(x, y)]
hanoi n x y z = hanoi (n - 1) x z y ++ [(x, y)] ++ hanoi (n - 1) z y x

main :: IO()
main = print (hanoi 8 "a" "b" "c")

permalink


Categories

Links