为什么不将所有功能定义为应用于应用的所有功能?

发布于 2025-01-17 07:40:18 字数 545 浏览 2 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

神仙妹妹 2025-01-24 07:40:18

一个缺点是您现在不能再将其用于普通布尔值。因此,您必须编写pure true&amp;&amp;纯错误而不是true&amp;&amp; false。而且,如果您想获得结果,则必须使用Runidentity :: Identity a - &gt;或类似的东西。

一个更微妙的问题是您提出的功能不那么懒惰。通常,程序员期望&amp;&amp;是短路的。因此,如果您写false&amp;&amp;未定义的,但是如果您编写纯False&amp;&amp;未定义。实际上,您想将其实现为单月:

(&&) :: Monad m => m Bool -> m Bool -> m Bool
x && y = do
  x' <- x
  if x
    then y
    else pure False

一种常见的选择是给它另一个名称,例如 &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 of True && False. And if you want to get at the result you'd have to use runIdentity :: 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 return False if you write False && undefined, but your function will get stuck if you write pure False && undefined. Really you'd want to implement it as a monad:

(&&) :: Monad m => m Bool -> m Bool -> m Bool
x && y = do
  x' <- x
  if x
    then y
    else pure False

A common alternative is to give it another name, e.g. <&&>.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文