2010-11-01 71 views
5

我已閱讀了所有有關F#中的值限制的內容,但我仍不明白。我有以下代碼:F#值限制

type tree<'a> = 
    | Nil 
    | Node of (tree<'a> * 'a * tree<'a>) 

let rec flatten = function 
    | Nil -> [] 
    | Node (Nil, b, Nil) -> [b] 
    | Node (l, h, p) -> List.concat [(flatten l);[h];(flatten p)] 

和編譯器顯示錯誤:

error FS0030: Value restriction. The value 'it' has been inferred to have generic type 
    val it : '_a list  
Either define 'it' as a simple data term, make it a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation. 

誰能幫助我?非常感謝;)

+2

你能提供代碼調用flatten?我可以編譯並運行這個示例就好了 – JaredPar 2010-11-01 19:10:27

+0

但是當我打電話弄扁Nill ;;有一個問題。 – 877 2010-11-01 20:01:35

回答

11

允許我使用我的心理調試技能。您不能撥打flatten Nil,因爲如編譯器所示,對於任何類型'a,結果可能是'a list。您必須添加類型註釋,例如(flatten Nil : int list)

在一個不相關的說明中,您在拼合定義中的第二種情況是不必要的,可以刪除,因爲它也包含在第三種情況中。

+2

PDS的+1 ..... – Daniel 2010-11-02 21:42:46

+0

至於無關的「平坦化定義中的第二個案例是不必要的,可以刪除,因爲它也包含在第三個案例中」,對於第二個案例性能會更好因爲它會減少很多額外的匹配? – ca9163d9 2015-06-22 03:19:28

+0

@ dc7a9163d9 - 是的,這當然是可能的。但是,如果性能不符合目標,我會默認最簡單的事情,只會引入這樣的優化。 – kvb 2015-06-22 15:54:17