Last active
April 24, 2016 00:09
-
-
Save amar47shah/c980a0a2fc2609fb9f84c6a427a9aaa8 to your computer and use it in GitHub Desktop.
Towers of Hanoi, with command-line interface
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Towers of Hanoi for three pegs | |
-- outputs a list of moves to transport a tower of specified size | |
-- from peg A to peg B, with peg C as reserve space. | |
-- | |
-- $ runghc hanoi.hs 3 | |
-- [("A","B"),("A","C"),("B","C"),("A","B"),("C","A"),("C","B"),("A","B")] | |
import System.Environment (getArgs) | |
main :: IO () | |
main = getArgs >>= print . hanoi "A" "B" "C" . read . head | |
type Peg = String | |
type Move = (Peg, Peg) | |
hanoi :: Peg -> Peg -> Peg -> Integer -> [Move] | |
hanoi _ _ _ n | n < 1 = [] | |
hanoi p q _ 1 = [(p, q)] | |
hanoi p q r n = hanoi p r q (n - 1) | |
++ hanoi p q r 1 | |
++ hanoi r q p (n - 1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment