Friday 29 April 2016

Haskell: Working with Negative numbers


To avoid parsing ambiguity, we must always enclose the Negative numbers in parenthesis. Suppose when you try to multiply a number 2 with number -3, you with get following kind of error.

*Main> 2 * -3

<interactive>:26:1:
    Precedence parsing error
        cannot mix * [infixl 7] and prefix `-' [infixl 6] in the same infix expression


If you use expression like `2*-3`, (no spaces between operators), you will get different error message. In this case compiler assumes `*-` as single operator.

*Main> 2*-3

<interactive>:34:2:
    Not in scope: *-
    Perhaps you meant one of these:
      *> (imported from Prelude), ** (imported from Prelude),
      * (imported from Prelude)


To resolve above issue, enclose the negative number in parenthesis.

*Main> 2 * (-3)
-6


Why to use parenthesis?
Suppose you want to evaluate an expression like ‘function1 -10`, Compiler can understand it in any of two ways.
a.   It can assume -10 as an argument to the function function1.
b.   It can assume subtract the value (-10) from the function1.

To avoid above kind of problems, negative numbers are always enclosed in parenthesis.

Previous                                                 Next                                                 Home

No comments:

Post a Comment