Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple use of ++: more efficient if I force the evaluation from right to left?

Tags:

haskell

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.

like image 825
Guillaume Chérel Avatar asked Nov 01 '11 15:11

Guillaume Chérel


People also ask

What is left to right evaluation?

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.

What can be used to change the order of evaluation expression?

The order of precedence can be altered by using parentheses around the parts of the mathematical expression that needs to be evaluated first.

When expression contains multiple operators then which operator will be evaluated first this depends on its priority is known as?

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.


2 Answers

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".

like image 89
Fred Foo Avatar answered Oct 21 '22 05:10

Fred Foo


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.

like image 37
Matt Fenwick Avatar answered Oct 21 '22 04:10

Matt Fenwick