Created
January 14, 2015 15:01
-
-
Save alskipp/8690b5018faf6cc2b2a4 to your computer and use it in GitHub Desktop.
The Towers of Hanoi – Haskell/Swift comparison
This file contains hidden or 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
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")] | |
-} |
This file contains hidden or 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
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")] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Details about the puzzle can be found here: http://en.wikipedia.org/wiki/Tower_of_Hanoi