Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't `-` (minus) work for operator sections? [duplicate]

Tags:

haskell

Based on the position, the partial applications in Haskell gets the correct answer.

Prelude> (/2) 10
5.0
Prelude> (2/) 10
0.2
Prelude> (+3) 10
13
Prelude> (3+) 10
13

However, for - operator, I got an error with (-3) as Haskell (seems to) interprets it as a value -3 not partial application.

Prelude> (-3) 10

<interactive>:4:1:
    Could not deduce (Num (a0 -> t))
      arising from the ambiguity check for ‘it’
    from the context (Num (a -> t), Num a)
      bound by the inferred type for ‘it’: (Num (a -> t), Num a) => t
      at <interactive>:4:1-7
    The type variable ‘a0’ is ambiguous
    When checking that ‘it’
      has the inferred type ‘forall a t. (Num (a -> t), Num a) => t’
    Probable cause: the inferred type is ambiguous

How to solve this issue to get 7 in this example?

like image 983
prosseek Avatar asked Mar 04 '15 15:03

prosseek


1 Answers

Use subtract. - is the only operator in Haskell, that occurs both in a prefix and binary infix variant:

let a = -3     -- prefix  variant
let b = (-3)   -- also prefix variant!
let c = 4 - 3  -- binary variant

Therefore, you would have to use (subtract 3) 10. See also section 3.4 in the Haskell 2010 report (emphasis mine):

The special form -e denotes prefix negation, the only prefix operator in Haskell, and is syntax for negate (e). The binary - operator does not necessarily refer to the definition of - in the Prelude; it may be rebound by the module system. However, unary - will always refer to the negate function defined in the Prelude. There is no link between the local meaning of the - operator and unary negation.

Prefix negation has the same precedence as the infix operator - defined in the Prelude (see Table 4.1 ). Because e1-e2 parses as an infix application of the binary operator -, one must write e1(-e2) for the alternative parsing. Similarly, (-) is syntax for (\ x y -> x-y), as with any infix operator, and does not denote (\ x -> -x)— one must use negate for that.

And section 3.5 concludes (again, emphasis mine):

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.

like image 84
Zeta Avatar answered Oct 02 '22 10:10

Zeta