为什么约束论的责任是将价值单位化? [英] Why is it bind's argument's responsibility to unit its value?

查看:81
本文介绍了为什么约束论的责任是将价值单位化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

典型的monad 绑定函数具有以下签名:

The typical monad bind function has the following signature:

m a -> (a -> m b) -> m b

据我所知(我可能错了),函数(a - > mb)只是一个从一个结构 a 到另一个 b 。假设这是正确的乞讨问题为什么绑定的签名不是简单的:

As I understand it (and I might well be wrong,) the function (a -> m b) is just a mapping function from one structure a to another b. Assuming that is correct begs the question why bind's signature is not simply:

m a -> (a -> b) -> m b

鉴于单位是monad的定义;为什么给函数(a - > mb)负责调用 unit 的任何值 b 它产生–将它放在 bind

Given that unit is part of a monad's definition; why give the function (a -> m b) the responsibility to call unit on whatever value b it produced – wouldn't it be more sensible to make it part of bind?

推荐答案

的一部分不是更明智吗? p>像 ma - >这样的函数(a - > b) - > m b 相当于 fmap ::(a - > b) - > f a - > f b 。所有 fmap 可以做的是更改动作内部的值,它不能执行新的动作。有了 m a - > (a - > m b) - > mb ,您可以运行 ma ,将该值输入(a - > mb),然后返回一个新的效果 mb 。如果没有这个,你只能在你的程序中有一个效果,你不能连续打印两条语句,你不能连接到网络,然后下载一个URL,而你无法响应用户输入,您只能转换每个基本操作返回的值。这个操作允许monad比函子或应用程序更强大。

A function like m a -> (a -> b) -> m b would be equivalent to fmap :: (a -> b) -> f a -> f b. All fmap can do is change the values inside the action, it can't perform new actions. With m a -> (a -> m b) -> m b, you can "run" the m a, feed that value into (a -> m b), then return a new effect of m b. Without this, you would only ever be able to have one effect in your program, you couldn't have two print statements sequentially, you couldn't connect to a network and then download a URL, and you couldn't respond to user input, you would only be able to transform the value returned from each primitive operation. It's this operation that allows monads to be more powerful than either functors or applicatives.

这里的另一个细节是,你不一定只用<$ c $包装一个值c> unit ,那 mb 可以代表一个动作,而不仅仅是返回一些东西。例如,在操作 putStrLn :: String - >中操作 return 的地方在哪里? m()?此函数的签名与>> = 的第二个参数兼容,其中 a〜String b〜(),但是在它的正文的任何​​地方都没有调用 return >> = 的要点是将两个动作排在一起,而不仅仅是将上下文中的值包裹起来。

Another detail here is that you aren't necessarily just wrapping a value with unit, that m b could represent an action, not just returning something. For example, where is the call to return in the action putStrLn :: String -> m ()? This function's signature is compatible with the second argument to >>=, with a ~ String and b ~ (), but there is not call to return anywhere in its body. The point of >>= is to sequence two actions together, not just to wrap values in a context.

这篇关于为什么约束论的责任是将价值单位化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆