Skip to content

Instantly share code, notes, and snippets.

@motylwg
Created February 17, 2015 16:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save motylwg/22ccf2dfa119f02e3b8f to your computer and use it in GitHub Desktop.
Save motylwg/22ccf2dfa119f02e3b8f to your computer and use it in GitHub Desktop.
Tower of Hanoi in F#
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