gpt4 book ai didi

f# - 如何在 F# 中添加增量计数器

转载 作者:行者123 更新时间:2023-12-04 18:29:42 28 4
gpt4 key购买 nike

我正在尝试做汉诺塔,但我不知道如何添加计数增量器。这是我的代码:

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

我试图让它打印出这样的东西
1: 1 3
2: 1 2
3: 3 2
etc...

我知道没有为
1:
2:
3:

部分。我知道正确的格式是
"%A: %A %A\n" *with some counter here* a b

但是我不知道该怎么做。我在网上寻找答案,但没有找到任何东西。如果有人可以帮助我,那将不胜感激。

先感谢您

最佳答案

s952163的comment是这里的正确答案,但这里有更多解释。
List.iteri看起来很像List.iter ,除了您的函数将有两个参数 - 计数器和列表元素。在这里,这看起来像

hanoi disks 1 2 |> List.iteri (fun i (a, b) -> printfn "%d: %d %d" i a b)

注意:我还包含了几种简化该行代码的方法,通过
  • 删除 hanoi 周围不必要的括号函数 - 管道操作符 |>具有非常低的优先级,因此通常不需要括号来分隔其参数
  • 使用 printfn而不是 printf "...\n" - 前者是首选,因为它将使用正确的行尾形式。在 Windows 上,这实际上是“\r\n”(尽管当您写入控制台时,这无关紧要)
  • 从 lambda 函数中删除模式匹配 - 您实际上并不是模式匹配,因为元组 (a, b)是一种类型本身。您可以直接在函数调用中获取参数,并节省一些输入。
  • 关于f# - 如何在 F# 中添加增量计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40598757/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com