gpt4 book ai didi

f# - 在声明之前使用变量/函数

转载 作者:行者123 更新时间:2023-12-05 01:35:41 25 4
gpt4 key购买 nike

我有一个我无法解析的递归:

module Test
type Command =
| Exit of string
| Action of string * (unit -> unit)

let getName command =
match command with
| Exit(n) -> n
| Action(n, _) -> n

let listCommands commands =
List.iter (getName >> printf "%s\n") commands

let hello () =
printf "Well, hi\n"

let help () =
printf "Available commands are:\n"
listCommands commands // <- ERROR IS HERE!!!, F# doesn't know of commands array

let commands = [
Exit("exit")
Action("hello", hello)
Action("help", fun() -> help)
]

listCommands commands // just some command to make module compile

在方法 help() 中,我使用列表 commands,它又引用方法 help()。我如何很好地打破这种递归?我可以做 mutable 等等,但这不是函数式风格。

最佳答案

您可以使用 let rec ... and 构造:

let rec help () = 
printf "Available commands are:\n"
listCommands commands
and commands = [
Exit("exit")
Action("hello", hello)
Action("help", help)
]

关于f# - 在声明之前使用变量/函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20543567/

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