2014-05-01 43 views
5

當我有這樣的代碼:創建遞歸識別聯合值

type HtmlNode = 
    | HtmlElement of name:string * attribute:HtmlAttribute list 
    | HtmlText of content:string 

and HtmlAttribute = 
    | HtmlAttribute of name:string * value:string * parent:HtmlNode 

let createElement name attrs = 
    let toAttributes element = [ for name, value in attrs -> HtmlAttribute(name, value, element)] 
    let rec element = HtmlElement(name, attributes) 
    and attributes = toAttributes element 
    element 

編譯器提供了以下錯誤:

Recursive values cannot appear directly as a construction of the type 'HtmlNode' within a recursive binding. This feature has been removed from the F# language. Consider using a record instead.

這是爲什麼? [讓REC應該支持遞歸值,並與記錄的類似的東西作品的創作。

+0

我沒有得到這個錯誤。 – eulerfx

+0

基於消息,這在最近的3.1版可能已被更改。發生 – Daniel

+0

同樣的錯誤在F#3.0 - 所以它是年齡稍大的 –

回答

2

我不知道爲什麼會被改變,但一個解決方法是使用seq而不是list

type HtmlNode = 
    | HtmlElement of name:string * attribute:HtmlAttribute seq 
    | HtmlText of content:string 

and HtmlAttribute = 
    | HtmlAttribute of name:string * value:string * parent:HtmlNode 

let createElement name attrs = 
    let rec element = HtmlElement(name, attributes) 
    and attributes = seq { for name, value in attrs -> HtmlAttribute(name, value, element) } 
    element 
+0

有趣的是,如果我傳遞一個列表或數組的序列,它崩潰在運行時 –

+0

我也注意到了。似乎需要一個間接的層面。 – Daniel