gpt4 book ai didi

recursion - 创建递归可区分联合值

转载 作者:行者123 更新时间:2023-12-04 21:16:03 25 4
gpt4 key购买 nike

当我有这个代码时:

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.



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

最佳答案

我不知道为什么会这样改变,但一种解决方法是使用 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

关于recursion - 创建递归可区分联合值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23406117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com