通过实例学F# - 汉诺塔(hanoi)
F#以递归方式解决汉诺塔问题:
#light
// count: number of the pallets.
// fromPole: the source pole for the pallets.
// toPole: the destination pole for the pallets.
// viaPole: a transfer pole for moving the pallets.
let rec hanoi(count, fromPole, viaPole, toPole) =
if (count = 1) then
printfn "%s -> %s" fromPole toPole
else begin
hanoi (count - 1, fromPole, toPole, viaPole)
printfn "%s -> %s" fromPole toPole
hanoi (count - 1, viaPole, fromPole, toPole)
end
// please move 4 pallets from the source pole "A" to the destination pole "C";
// pole "B" can be used for any transfer.
hanoi(4, "A", "B", "C")
// count: number of the pallets.
// fromPole: the source pole for the pallets.
// toPole: the destination pole for the pallets.
// viaPole: a transfer pole for moving the pallets.
let rec hanoi(count, fromPole, viaPole, toPole) =
if (count = 1) then
printfn "%s -> %s" fromPole toPole
else begin
hanoi (count - 1, fromPole, toPole, viaPole)
printfn "%s -> %s" fromPole toPole
hanoi (count - 1, viaPole, fromPole, toPole)
end
// please move 4 pallets from the source pole "A" to the destination pole "C";
// pole "B" can be used for any transfer.
hanoi(4, "A", "B", "C")
Note:
#light - Lightweight syntax, 是为了保持语法兼容Caml系列语言,F#从Caml系列语言发展而来。微软建议在代码中保留此关键字。
代码缩进 - light代码不允许TAB缩进。
rec - 表明该函数为递归函数,即可以调用本身。
begin/end - 同C系列语言不同,F#以begin/end 定义语句块。
printfn - 同C系列语言的打印函数基本类似。
浙公网安备 33010602011771号