Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can (<$>) be left associative

I just noticed that (<$>) has a fixity of infixl 4. How can this be?

(+1) <$> (/5) <$> [5,10] obviously works right to left.

like image 518
hgiesel Avatar asked Apr 15 '17 14:04

hgiesel


People also ask

Which operator is left-associative?

In order to reflect normal usage, addition, subtraction, multiplication, and division operators are usually left-associative, while for an exponentiation operator (if present) and Knuth's up-arrow operators there is no general agreement.

What is right to left associativity?

Associativity is the left-to-right or right-to-left order for grouping operands to operators that have the same precedence. An operator's precedence is meaningful only if other operators with higher or lower precedence are present. Expressions with higher-precedence operators are evaluated first.

Is ++ right or left-associative?

For example + and – have the same associativity. Precedence of postfix ++ is more than prefix ++, their associativity is also different. Associativity of postfix ++ is left to right and associativity of prefix ++ is right to left.

Are relational operators left-associative?

Relational operators have left to right associativity. Left to right associativity means that when two operators of same precedence are adjacent, the left most operator is evaluated first.


1 Answers

No, <$> is left associative and this is no different in your example. (+1) <$> (/5) <$> [5,10] is read as ((+1) <$> (/5)) <$> [5,10]. This happens to work because of the Functor instance of (->) a is basically equivalent to function composition; fmap (+1) (/5) is equivalent to \x -> (x/5)+1, which in this instance gives you the same result as what you'd get with the order you appear to think this works in, i.e. (+1) <$> ((+5) <$> [5,10]).

Because this is a little bit confusing, if you want to apply multiple functions in a row it's probably better for readability to use the normal function composition operator here: (+1) . (/5) <$> [5,10].

like image 66
Cubic Avatar answered Oct 23 '22 00:10

Cubic