+1 和 -1 之间的区别
> :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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为
(-1)
被解释为负数,而(+1)
被解释为柯里化函数(\x->1+x )
。在 haskell 中,
(a **)
是(**) a
的语法糖,而(** a)
是( \x -> x ** a)
。然而(-)
是一种特殊情况,因为它既是一元运算符(否定)又是二元运算符(减号)。因此,这个语法糖不能明确地应用在这里。当您想要(\x -> a - x)
时,您可以编写(-) a
,并且,正如 柯里化减法,您可以使用函数negate
和subtract
来消除一元和二进制之间的歧义-
函数。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 functionsnegate
andsubtract
to disambiguate between the unary and binary-
functions.我刚刚找到了一个名为
subtract
的函数,所以我也可以说subtract 1
。我发现这很有可读性:-)I just found a function called
subtract
, so I can also saysubtract 1
. I find that quite readable :-)正如其他人所指出的,
(-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)
.