16

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

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

hgiesel
  • 5,430
  • 2
  • 29
  • 56

1 Answers1

18

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

Cubic
  • 14,902
  • 5
  • 47
  • 92
  • So, it does not really matter if it is left or right associative, as far as semantics is concerned (and functors indeed satisfy functor laws). I wonder if the left associaitvity was a deliberate choice, e.g. for perfomance reasons. It could even have been defined in that way by chance, or by error, in theory. – chi Apr 15 '17 at 18:11
  • 2
    @chi If `(<$>)` were right associative, you could no longer use that `f <$> x <*> y` style pattern (because `(<*>)` would also have to be right associative, for you to use them together without parentheses like that). There are some people who say that `($)` should have been left associative, because then you could do something like `f $ g x $ h y` and it would be equivalent to `f (g x) (h y)` (and I guess it would be symmetrical with how `->` is right associative). Of course, it really comes down to preference though. – David Young Apr 17 '17 at 17:31