13
> :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?

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
fredoverflow
  • 256,549
  • 94
  • 388
  • 662

3 Answers3

9

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.

Community
  • 1
  • 1
HaskellElephant
  • 9,819
  • 4
  • 38
  • 67
  • 5
    "Negation is the only prefix operator in Haskell" http://www.haskell.org/onlinereport/exps.html – Matthew Gilliard Mar 06 '11 at 11:40
  • @mjg123, I think writing "the unary operator" rather then "a unary operator" here only makes it harder to get the message which is "its both unary and binary." Therefor I think I will leave it as it is. =D – HaskellElephant Apr 05 '11 at 06:48
6

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

fredoverflow
  • 256,549
  • 94
  • 388
  • 662
  • 1
    +1 `subtract` was made specifically for use in sections. [Haskell 2010 / Expressions # Sections](http://www.haskell.org/onlinereport/haskell2010/haskellch3.html#x8-300003.5) "Because - is treated specially in the grammar, `(- exp)` is not a section, but an application of prefix negation, as described in the preceding section. However, there is a `subtract` function defined in the Prelude such that `(subtract exp)` is equivalent to the disallowed section. The expression `(+ (- exp))` can serve the same purpose." – Dan Burton Mar 06 '11 at 18:49
1

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

Fred Foo
  • 355,277
  • 75
  • 744
  • 836