我有一个无法解决的递归:
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
Run Code Online (Sandbox Code Playgroud)
在方法help()I中,使用list commands,而list 又引用了方法help().我如何很好地打破这种递归?我可以做多变等等,但这不是一种功能风格.
你可以使用let rec ... andconstruct:
let rec help () =
printf "Available commands are:\n"
listCommands commands
and commands = [
Exit("exit")
Action("hello", hello)
Action("help", help)
]
Run Code Online (Sandbox Code Playgroud)