Created
February 17, 2015 16:56
-
-
Save motylwg/22ccf2dfa119f02e3b8f to your computer and use it in GitHub Desktop.
Tower of Hanoi in F#
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
type Peg = | |
| A | |
| B | |
| C | |
type Move = | |
| Move of int * Peg * Peg | |
static member toString m = | |
match m with | |
| Move(n, p1, p2) when n <> 1 -> sprintf "move %i %A %A" n p1 p2 | |
| Move(_, p1, p2) -> sprintf "%A->%A" p1 p2 | |
let move n p1 p2 = Move(n, A, B) | |
// solve with: move n A B |> hanoi | |
let hanoi x = | |
let pegs = Set.ofList [A; B; C] | |
let free (p1 : Peg) (p2: Peg) = | |
pegs |> Set.remove p1 |> Set.remove p2 |> Set.toList |> List.head | |
let rec expand move = | |
match move with | |
| Move (n, a, b) when n = 1 -> [Move (n, a, b)] | |
| Move (n, a, b) -> | |
let f = free a b | |
expand (Move(n-1, a, f)) @ [Move(1, a, b)] @ expand (Move(n-1, f, b)) | |
let moves = expand x | |
List.map Move.toString moves |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment