Skip to content

Instantly share code, notes, and snippets.

@alskipp
Created January 14, 2015 15:01
Show Gist options
  • Save alskipp/8690b5018faf6cc2b2a4 to your computer and use it in GitHub Desktop.
Save alskipp/8690b5018faf6cc2b2a4 to your computer and use it in GitHub Desktop.
The Towers of Hanoi – Haskell/Swift comparison
type Peg = String
type Move = (Peg, Peg)
hanoi :: Integer -> Peg -> Peg -> Peg -> [Move]
hanoi 0 _ _ _ = []
hanoi n a b c = hanoi (n-1) a c b ++ [(a,b)] ++ hanoi (n-1) c b a
{-
Usage:
hanoi 3 "a" "b" "c"
Result:
[("a","b"),("a","c"),("b","c"),("a","b"),("c","a"),("c","b"),("a","b")]
-}
typealias Peg = String
typealias Move = (Peg, Peg)
func hanoi(n:Int, a:Peg, b:Peg, c:Peg) -> [Move] {
switch n {
case 0 : return []
default : return hanoi(n-1, a, c, b) + [(a,b)] + hanoi(n-1, c, b, a)
}
}
/*
Usage:
hanoi(3, "a", "b", "c")
Result:
[("a","b"),("a","c"),("b","c"),("a","b"),("c","a"),("c","b"),("a","b")]
*/
@alskipp
Copy link
Author

alskipp commented Jan 14, 2015

Details about the puzzle can be found here: http://en.wikipedia.org/wiki/Tower_of_Hanoi

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