Haskell 使用 >=> 编写 >>=单子
(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> (a -> m c)
bind :: Monad m => m a -> (a -> m b) -> m b
-- 如何使用>=>
来编写bind
?
我非常困惑,我明白这两者是如何工作的,但我什至无法开始。
我尝试了以下所有替代方案:
bind1 a b = (b a)
bind2 a b = (a >=> b)
bind3 a b = (b >=> a)
bind4 a b = (a b)
但每次尝试都会引发错误。我可以从哪里开始回答这个问题?
由于 >>=
有 2 个参数,而 >=>
有 3 个参数,我如何使用 >=>
来少1个参数时要写>>=
吗?
(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> (a -> m c)
bind :: Monad m => m a -> (a -> m b) -> m b
-- how do you use >=>
to write bind
?
I am absolutely so confused, I understand how both of these works but I cant even get started.
I tried all the following alternatives:
bind1 a b = (b a)
bind2 a b = (a >=> b)
bind3 a b = (b >=> a)
bind4 a b = (a b)
but every single attempt raises an error. Where can i possibly start on this question?
Since >>=
has 2 parameters, and >=>
has 3, how can I use >=>
to write >>=
when there is 1 less parameter?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,我建议重命名类型参数,以便最终结果匹配:
现在我们有一个
b ->;第一个签名中的 m c
和a -> m c
在第二个;建议将a
重命名为b
:主要区别在于有一个额外的参数
a
。但我们显然不需要它,所以我们不妨将其专门化为无信息类型()
(或任何其他单值类型):() -> m x
实际上与单独的m x
同构:这只是使用这些转换函数来使函数相互适应的问题。
First I'd suggest renaming the type parameters so the final result matches:
Now we have a
b -> m c
in the first signature anda -> m c
in the second; that suggests renaming alsoa
tob
:That leaves the main difference as having an extra argument
a
. But we evidently don't need that, so we might as well specialize it to the information-less type()
(or any other single-value type):() -> m x
is actually isomorphic tom x
alone:And it's just a matter of using those conversion functions to adapt the functions to each other.
Haskell 中的每个函数都有一个参数。您可以将
>=>
解释为第一个参数为a ->; 类型的函数。 m b
和 b -> 的第二个内容m c,a -> m c
是“结果”函数。您在这里可以做的是将
bind
的第一个参数操作为接受参数的函数,然后提供该参数,例如:这里使用
const ma
,因此我们创建一个带有我们不关心的参数的函数,然后构造一个a ->; m c
通过使用>=>
并使用undefined
(或其他值)调用它来生成m c
值。Each function in Haskell has one parameter. You can interpret
>=>
, as a function that has as first parameter something of typea -> m b
and the second something ofb -> m c
, thea -> m c
is the "result" function.What you here can do is manipulate the first parameter of
bind
into a function that accepts a parameter, and then provide that parameter, something like:Here with
const ma
, we thus create a function that takes a parameter we do not care about, then we construct ana -> m c
by using>=>
and we call it withundefined
(or some other value) to produce them c
value.