变量/函数声明之前

问题描述:

我有无法解析递归:变量/函数声明之前

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

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

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

非常感谢!你救了我) – Rustam

+0

@Rustam没问题,很高兴我可以帮助:) –