Why does `` `` (minus) not work for operator sections?

Depending on the position, partial applications in Haskell get the correct answer.

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

However, for the operator, I got an error with (-3) , because Haskell (seems) interprets it as the value -3 not a 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 problem to get 7 in this example?

+6
source share
1 answer

Use subtract . - - the only operator in Haskell that occurs both in the prefix and in the binary version of the infix:

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

Therefore, you will need to use (subtract 3) 10 . See also the section in the Haskell 2010 report (highlighted by me):

The special form -e stands for prefix negation, the operator is only a prefix in Haskell and is the syntax for negate (e) . A binary operator - does not necessarily refer to a definition - in foreplay; It can be restored by a system of modules. However, unary will always refer to the negate function defined in Prelude. There is no connection between the local value of the operator - and unary negation.

Denial of the prefix has the same priority as the infix operator - defined in the prelude (see table 4.1). Since e1-e2 parses as an infix application of the binary operator - , you need to write e1(-e2) for alternative parsing. Similarly, (-) is the syntax for (\ xy -> xy) , as well as for any infix operator, and does not mean (\ x -> -x) - you need to use negate for this.

And section 3.5 concludes (again, my emphasis):

Since - processed specifically in the grammar, (- exp) is not a section, but a prefix negation application, as described in the previous section. However, there is a subtract function defined in Prelude such that (subtract exp) equivalent to a forbidden section. The expression (+ (- exp)) can serve the same purpose.

+15
source

Source: https://habr.com/ru/post/983327/


All Articles