2013-12-12 53 views
3

我有無法解析遞歸:變量/函數聲明之前

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()。我如何很好地打破這種遞歸?我可以做可變的等等,但這不是一種功能性的風格。

回答

5

您可以使用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沒問題,很高興我可以幫助:) –