Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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

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

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)

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.

This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

Haskell: Working with Negative numbers


Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription