F# 中的自定义计算表达式
我一直在玩弄 F# 中的 monad(又名计算表达式),并且编写了这个简单的 Identity monad:
type Identity<'a> =
| Identity of 'a
type IdentityBuilder() =
member x.Bind (Identity v) f = f(v)
member x.Return v = Identity v
let identity = new IdentityBuilder()
let getInt() = identity { return Int32.Parse(Console.ReadLine()) }
let calcs() = identity {
let! a = getInt() // <- I get an error here
let! b = getInt()
return a + b }
我不明白我在标记行中遇到的错误:
该表达式的类型应为 Identity<'a>但这里有类型 'b * 'c
我认为这没有意义,因为 getInt() 显然是 Identity<'a>
类型的值。
谁能告诉我我做错了什么?
I've been toying with monads in F# (aka computation expressions) and I wrote this simple Identity monad:
type Identity<'a> =
| Identity of 'a
type IdentityBuilder() =
member x.Bind (Identity v) f = f(v)
member x.Return v = Identity v
let identity = new IdentityBuilder()
let getInt() = identity { return Int32.Parse(Console.ReadLine()) }
let calcs() = identity {
let! a = getInt() // <- I get an error here
let! b = getInt()
return a + b }
I don't understand the error I'm getting in the marked line:
This expression was expected to have type Identity<'a> but here has type 'b * 'c
I think this makes no sense as getInt() is clearly a value of type Identity<'a>
.
Can anyone tell me what am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
计算表达式语法希望 Bind 有一个元组参数,而不是柯里化参数。
因此,
请参阅本文了解所有签名。
The computation expression syntax wants
Bind
to have a tupled, not curried argument.So
See this article for all signatures.
问题在于您的 Bind 函数的类型 - 它不应该采用柯里化参数。如果你将其更改为:
那么它应该可以工作。
The problem is the type of your
Bind
function - it shouldn't take curried arguments. If you change it to:then it should work.