I just noticed that (<$>)
has a fixity of infixl 4
. How can this be?
(+1) <$> (/5) <$> [5,10]
obviously works right to left.
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.
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.
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.
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.
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]
.
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