tl;dr
The r
and l
refer to the associativity, the number you specify refers to the operator precedence. When you don't specify the associativity you get an operator that can be associated only by explicit parenthesis or when the associativity is non-ambiguous.
Our test data structure
Let's use a data structure to define operators on and understand how associativity works:
data Test = Test String deriving (Eq, Show)
It will contain the string built with the below operators.
Associativity with infixr
and infixl
Now let's define right- and left- associative operators:
(>:) :: Test -> Test -> Test
(Test a) >: (Test b) = Test $ "(" ++ a ++ " >: " ++ b ++ ")"
(<:) :: Test -> Test -> Test
(Test a) <: (Test b) = Test $ "(" ++ a ++ " <: " ++ b ++ ")"
infixr 6 >:
infixl 6 <:
These operator will construct the string of the resulting operator by explicitly adding the parenthesis to our associated terms.
If we test it out we see that it works correctly:
print $ (Test "1") >: (Test "2") >: (Test "4")
-- Test "(1 >: (2 >: 4))"
print $ (Test "1") <: (Test "2") <: (Test "4")
-- Test "((1 <: 2) <: 4)"
"Associativity" with infix
An infix
declaration does not specify associativity. So what should happen in those cases? Let's see:
(?:) :: Test -> Test -> Test
(Test a) ?: (Test b) = Test $ "(" ++ a ++ " ?: " ++ b ++ ")"
infix 6 ?:
And then let's try it:
print $ (Test "1") ?: (Test "2") ?: (Test "4")
Woops, we get:
Precedence parsing error
cannot mix `?:' [infix 6] and `?:' [infix 6] in the same infix expression
As you can see the language parser noticed that we didn't specify the associativity of the operator and doesn't know what to do.
If we instead remove the last term:
print $ (Test "1") ?: (Test "2")
-- Test "(1 ?: 2)"
Then the compiler doesn't complain.
To fix the original term we would need to explicitly add parenthesis; for example:
print $ (Test "1") ?: ((Test "2") ?: (Test "4"))
-- Test "(1 ?: (2 ?: 4))"
Live demo
l/r/<nothing>
) tells how to group when there are many copies of that operator; the precedence (1-9
) tells how to group when there are many different operators. – Gingrich