Mar*_*ram 5 f# counter increment towers-of-hanoi
我正在尝试做河内塔,但我不知道如何添加计数增量器.这是我的代码:
open System
let disks = Int32.Parse(Console.ReadLine())
let rec hanoi num start finish =
match num with
| 0 -> [ ]
| _ -> let temp = (6 - start - finish)
(hanoi (num-1) start temp) @ [ start, finish ] @ (hanoi (num-1) temp finish)
[<EntryPoint>]
let main args =
(hanoi disks 1 2) |> List.iter (fun pair -> match pair with
| a, b -> printf ": %A %A\n" a b)
0
Run Code Online (Sandbox Code Playgroud)
我正试图打印出类似这样的东西
1: 1 3
2: 1 2
3: 3 2
etc...
Run Code Online (Sandbox Code Playgroud)
我知道没有格式化设置
1:
2:
3:
Run Code Online (Sandbox Code Playgroud)
部分.我知道正确的格式是
"%A: %A %A\n" *with some counter here* a b
Run Code Online (Sandbox Code Playgroud)
但是我不知道该怎么做.我在网上寻找答案,但我没有找到任何答案.如果有人能帮助我,我将不胜感激.
先感谢您
s952163的评论是正确的答案,但这里有更多的解释.
List.iteri看起来非常相似List.iter,除了你的函数将有两个参数 - counter和list元素.在这里,这看起来像
hanoi disks 1 2 |> List.iteri (fun i (a, b) -> printfn "%d: %d %d" i a b)
Run Code Online (Sandbox Code Playgroud)
注意:我还提供了几种简化代码行的方法
hanoi函数周围不必要的括号- 管道运算符的|>优先级非常低,因此通常不需要括号来分隔其参数printfn而不是printf "...\n"- 前者是首选,因为它将使用正确的行结尾形式.在Windows上,这实际上是"\ r \n"(虽然当你写入控制台时,无所谓)(a, b)本身就是一个类型.您可以直接在函数调用中获取参数,并节省一些输入.