gpt4 book ai didi

f# - 为什么 F# 计算表达式需要构建器对象(而不是类)?

转载 作者:行者123 更新时间:2023-12-03 01:11:52 25 4
gpt4 key购买 nike

F# 计算表达式的语法如下:

ident { cexpr }

其中 ident 是构建器对象(此语法取自 Don Syme's 2007 blog entry )。

在我见过的所有示例中,构建器对象都是单例实例,并且无状态启动。 Don 给出了定义名为 attempt 的构建器对象的示例:

let attempt = new AttemptBuilder()

我的问题:为什么 F# 不直接在计算表达式中使用 AttemptBuilder 类?当然,静态方法调用的符号可以像实例方法调用一样容易地去糖化。

使用实例值意味着理论上可以实例化同一类的多个构建器对象,可能以某种方式参数化,甚至(但愿不会)具有可变的内部状态。但我无法想象这会有什么用处。

<小时/>

更新:我上面引用的语法表明构建器必须显示为单个标识符,这是误导性的,并且可能反射(reflect)了该语言的早期版本。最新F# 2.0 Language Specification定义语法为:

expr { comp-or-range-expr }

这清楚地表明任何表达式(计算结果为构建器对象)都可以用作构造的第一个元素。

最佳答案

你的假设是正确的;构建器实例可以参数化,并且随后可以在整个计算过程中使用参数。

我使用这种模式来构建特定计算的数学证明树。每个结论都是问题名称计算结果底层结论的N树的三元组(引理)。

让我提供一个小例子,删除证明树,但保留问题名称。我们将其称为注释,因为它看起来更合适。

type AnnotationBuilder(name: string) =
// Just ignore an original annotation upon binding
member this.Bind<'T> (x, f) = x |> snd |> f
member this.Return(a) = name, a

let annotated name = new AnnotationBuilder(name)

// Use
let ultimateAnswer = annotated "Ultimate Question of Life, the Universe, and Everything" {
return 42
}
let result = annotated "My Favorite number" {
// a long computation goes here
// and you don't need to carry the annotation throughout the entire computation
let! x = ultimateAnswer
return x*10
}

关于f# - 为什么 F# 计算表达式需要构建器对象(而不是类)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12339223/

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