On Haskell’s (-)s

And then I learned about Haskell’s only unary operator, the minus sign… I discovered it working through one of the book’s sections on div and quot…

> -11 `div` 3
> -11 `quot` 3

Wait, what? The exercises suggested I should expect -4. Oh, they had some parentheses…

> (-11) `quot` 3
> (-11) `div` 3

Okay, cool. But what’s really going on here?  Apparently Haskell has some syntactic sugar to make negative numbers work. It’s using the “negate” function under the hood. Hmm, what about its precedence?

> negate 11 ^ 2
> negate (11 ^ 2)

Hmm, okay I had to looked this up, and it turns out function application precedence is the highest possible. So in the first example the negate is applied to 11 first, then squared, hence positive 121.

> -11^2

Huh? I thought the unary operator was syntactic sugar for negate… a function. Ack. I don’t know how to look up the “info” for the unary operator to see its precedence. I guess it’s lower than exponentiation.

Okay, so at the end of the day, -11^2 works the way it does in other languages (e.g. -11**2 in Python), so there’s no issue there, but the way that I arrived was a bit strange. Lesson learned though: parenthesize your negative numbers if that’s what you mean.

The one casualty here is sectioning with the (-) operator:

> (+3) 4
> (-3) 4
[... error: you tried to apply a number (negate 3) as a function...]

What if you really want to do this? Use the subtract function, for example:

> (subtract 3) 4

Of course that made me realize that (subtract x y) means “subtract x from y”:

> subtract 3 4
-- (subtract x y) == (y - x)

Fine, I’ll live with it. In any case, I can say Haskell’s positives still far outweigh its negatives.

(… Of course the next section of the Haskell Book promptly covered this. More than a little impressed that they did!)

Gory details here: https://wiki.haskell.org/Unary_operator

And here: https://www.haskell.org/onlinereport/exps.html (See section 3.4)


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s