为什么不将所有功能定义为应用于应用的所有功能?
internalAnd :: Bool -> Bool -> Bool
internalAnd True True = True
internalAnd _ _ = False
(&&) :: Applicative m => m Bool -> m Bool -> m Bool
(&&) = liftA2 internalAnd
-- Usage
greaterThan x = (x <)
lessThan x = (x >)
validateAge = greaterThan 0 && lessThan 120 -- It's really useful with combinators.
我认为对于许多情况(例如制作组合器)来说,在 Applicative 上定义所有函数非常有用。而applicative是对适用性的抽象,对应于函数的能力,所以这样做似乎也不错。
通过 Applicative 定义所有函数会出现什么问题?
internalAnd :: Bool -> Bool -> Bool
internalAnd True True = True
internalAnd _ _ = False
(&&) :: Applicative m => m Bool -> m Bool -> m Bool
(&&) = liftA2 internalAnd
-- Usage
greaterThan x = (x <)
lessThan x = (x >)
validateAge = greaterThan 0 && lessThan 120 -- It's really useful with combinators.
I think it is useful to define all functions over Applicative
for many situation like making combinators. And applicative is abstraction of applicability that is corresponding to function's ability, so it seems not bad to do like this.
What is expected problems of defining all the functions over Applicative
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一个缺点是您现在不能再将其用于普通布尔值。因此,您必须编写
pure true&amp;&amp;纯错误
而不是true&amp;&amp; false
。而且,如果您想获得结果,则必须使用Runidentity :: Identity a - &gt;
或类似的东西。一个更微妙的问题是您提出的功能不那么懒惰。通常,程序员期望
&amp;&amp;
是短路的。因此,如果您写false&amp;&amp;未定义的
,但是如果您编写纯False&amp;&amp;未定义
。实际上,您想将其实现为单月:一种常见的选择是给它另一个名称,例如
&lt;&amp;&gt;
。One disadvantage is that you now cannot use it for normal booleans anymore. So, you'd have to write
pure True && pure False
instead ofTrue && False
. And if you want to get at the result you'd have to userunIdentity :: Identity a -> a
or something like that.A more subtle problem is that your proposed function is less lazy. Usually, programmers expect
&&
to be short-circuiting. So it should still returnFalse
if you writeFalse && undefined
, but your function will get stuck if you writepure False && undefined
. Really you'd want to implement it as a monad:A common alternative is to give it another name, e.g.
<&&>
.