Skip to content

Instantly share code, notes, and snippets.

@elvinio
Created February 24, 2015 07:32
Show Gist options
  • Save elvinio/4115893d9e62fc9a130f to your computer and use it in GitHub Desktop.
Save elvinio/4115893d9e62fc9a130f to your computer and use it in GitHub Desktop.
Solving the Tower of Hanoi in Haskell
hanoi 0 _ _ _ = []
hanoi n a b c = hanoi (n-1) a c b ++ [(a,b)] ++ hanoi (n-1) c b a
han 0 _ _ _ = []
han n a b c = han (n-1) a c b ++ [(a,c)] ++ han (n-1) b a c
@elvinio
Copy link
Author

elvinio commented Feb 24, 2015

ghci> han 3 "A" "B" "C"
[("A","C"),("A","B"),("C","B"),("A","C"),("B","A"),("B","C"),("A","C")]

ghci> hanoi 4 "A" "B" "C"
[("A","C"),("A","B"),("C","B"),("A","C"),("B","A"),("B","C"),("A","C"),("A","B"),("C","B"),("C","A"),("B","A"),("C","B"),("A","C"),("A","B"),("C","B")]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment