开发者

The difference between +1 and -1

开发者 https://www.devze.com 2023-02-15 15:30 出处:网络
> :t (+1) (+1) :: Num a => a -> a > :t (-1) (-1) :: Num a => a How come the sec开发者_开发技巧ond one is not a function? Do I have to write (+(-1)) or is there a better way?This is b
> :t (+1)
(+1) :: Num a => a -> a

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

How come the sec开发者_开发技巧ond one is not a function? Do I have to write (+(-1)) or is there a better way?


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.


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 :-)


(-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).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号