+1 和 -1 之间的区别

发布于 2024-10-20 06:42:52 字数 158 浏览 5 评论 0原文

> :t (+1)
(+1) :: Num a => a -> a

> :t (-1)
(-1) :: Num a => a

为什么第二个不是函数?我必须写 (+(-1)) 还是有更好的方法?

> :t (+1)
(+1) :: Num a => a -> a

> :t (-1)
(-1) :: Num a => a

How come the second one is not a function? Do I have to write (+(-1)) or is there a better way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

傻比既视感 2024-10-27 06:42:52

这是因为 (-1) 被解释为负数,而 (+1) 被解释为柯里化函数 (\x->1+x )

在 haskell 中,(a **)(**) a 的语法糖,而 (** a)( \x -> x ** a)。然而 (-) 是一种特殊情况,因为它既是一元运算符(否定)又是二元运算符(减号)。因此,这个语法糖不能明确地应用在这里。当您想要 (\x -> a - x) 时,您可以编写 (-) a,并且,正如 柯里化减法,您可以使用函数 negatesubtract 来消除一元和二进制之间的歧义- 函数。

This is because (-1) is interpreted as negative one, however (+1) is interpreted as the curried function (\x->1+x).

In haskell, (a **) is syntactic sugar for (**) a, and (** a) is (\x -> x ** a). However (-) is a special case since it is both a unary operator (negate) and a binary operator (minus). Therefore this syntactic sugar cannot be applied unambiguously here. When you want (\x -> a - x) you can write (-) a, and, as already answered in Currying subtraction, you can use the functions negate and subtract to disambiguate between the unary and binary - functions.

向日葵 2024-10-27 06:42:52

我必须写(+(-1))还是有更好的方法?

我刚刚找到了一个名为 subtract 的函数,所以我也可以说 subtract 1。我发现这很有可读性:-)

Do I have to write (+(-1)) or is there a better way?

I just found a function called subtract, so I can also say subtract 1. I find that quite readable :-)

安静 2024-10-27 06:42:52

正如其他人所指出的,(-1) 是负数。减一函数是\x -> x-1翻转 (-) 1 或实际上 (+ (-1))

-表达式语法+ 不是,大概是因为正文字不需要前导加号,允许它会导致更多混乱。

编辑:我第一次弄错了。 ((-) 1) 是函数“减一”,或 (\x -> 1-x)

(-1) is negative one, as others have noted. The subtract one function is \x -> x-1, flip (-) 1 or indeed (+ (-1)).

- is treated as a special case in the expression grammar. + is not, presumably because positive literals don't need the leading plus and allowing it would lead to even more confusion.

Edit: I got it wrong the first time. ((-) 1) is the function "subtract from one", or (\x -> 1-x).

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