创建递归区分联合值

时间:2014-05-01 10:42:58

标签: recursion f# discriminated-union

当我有这段代码时:

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

编译器出现以下错误:

  

递归值不能直接显示为递归绑定中“HtmlNode”类型的构造。此功能已从F#语言中删除。请考虑使用记录。

为什么? let rec应该支持创建递归值,类似的东西也可以用于记录。

1 个答案:

答案 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