I want to append 3 lists or more at once in a single expression.
a ++ b ++ c
Will the ++ operator will be evaluated from left to right or right to left?
1. (a ++ b) ++ c
2. a ++ (b ++ c)
I would say option 2, because if ++ was a prefix function, we would write ++ a ++ b c
which naturally leads to evaluating ++ b c
first. I'm not sure if I'm correct.
But if it's option 1, it seems to me that explicitely changing the order of evaluation from right to left is more efficient:
a ++ (b ++ c)
Here is why: a ++ b ++ c
will first evaluate to ab ++ c
in n steps (where n is the length of a and ab is of course the concatenation of a and b) and then to abc
in n+m more steps (m being the length of b, thus n+m the is the length of ab), which makes a total of 2n+m steps. Whereas a ++ (b ++ c)
will first evaluate to a ++ bc
in m steps, and then to abc
in n more steps, which is a total of n+m steps only.
I'm new to haskell and not sure about what I'm saying, I'd like some confirmation.
When there are two (or more) operators of equal precedence, evaluate the expression from left to right. Since both operators are * , each has equal precedence, so calculate 2 * 7 first, then use that result with the second operator.
The order of precedence can be altered by using parentheses around the parts of the mathematical expression that needs to be evaluated first.
Operator precedence specifies the manner in which operands are grouped with operators. For example, 1 + 2 * 3 is treated as 1 + (2 * 3), whereas 1 * 2 + 3 is treated as (1 * 2) + 3 because the multiplication operator has a higher precedence than the addition operator.
a ++ b ++ c
is parsed as
a ++ (b ++ c)
for exactly the reasons you describe: had (++)
been left-associative, then a ++ b ++ c
would copy a
twice. You can check this in GHCi with
Prelude> :i (++)
which will respond with
infixr 5 ++
where infixr
means "infix, right-associative".
From ghci
, do a :i
:
Prelude> :i (++)
(++) :: [a] -> [a] -> [a] -- Defined in GHC.Base
infixr 5 ++
Which shows that ++
is (infix and) right-associative, and will be evaluated right-to-left. I don't know, but I would be willing to bet that whoever implemented that had your question in mind when he/she made it right-associative.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With