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

时间:2013-12-12 12:27:46

标签: f#

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

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()则引用方法{{1}}。我如何很好地打破这种递归?我可以做多变等等,但这不是一种功能性的风格。

1 个答案:

答案 0 :(得分:5)

您可以使用let rec ... and construct:

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