I am starting to learn Haskell with the book Learn You a Haskell for Great Good! , I come from using Python which is an imperative language. I am using the interpreter ghci
and ran into the following:
Prelude> 5 * -3
<interactive>:2:1:
Precedence parsing error
cannot mix `*' [infixl 7] and prefix `-' [infixl 6] in the same infix expression
From the error I understand that I cannot mix *
with -
in the expression, in the book they do not explain the reason why it does not work, they only recommend using parentheses:
Prelude> 5 * (-3)
-15
It occurs to me that it -
is treated as a function and that is why when enclosing it in parentheses it is evaluated first before multiplying. So I tried the following:
Prelude> -(5)
-5
Prelude> +(5)
<interactive>:9:1: parse error on input `+'
Well now I'm confused. why is it not possible to multiply a negative number without the need to use parentheses?
The reason is: because the grammar does not allow it . Let me go into a little detail about this.
Now let's see the error, it says:
What does this mean? Well, to begin with, let's define what they mean by
infixl 7
einfixl 6
, in their grammar there is something like this:What the error is telling you is that you can't mix elements
infixl 7
withinfixl 6
, that's the same reason you can't do something like this:Since the syntax error is thrown ( you can try it here ):
Wait, if it's a syntax error, why is the error above different?
It turns out that el
operador unario "-"
is very special and is used by other parts of the grammar, so in theory this goes down a different branch of the syntax tree and fails elsewhere.If you want to read more about the latter you can see here (in English) .