Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the dot compose from right to left in Haskell?

If we have two functions, f and g, then in Haskell h = f . g is equivalent to h x = f(g x). I.e. the functions are applied from right to left to the input. Is there any fundamental reason why it goes from right to left, and not from left to right? I.e. why didn't they make h = f . g equivalent to h x = g(f x) instead?

EDIT: as others pointed out my equivalent functions where the wrong way around, so I fixed those.

like image 334
Tiddo Avatar asked Apr 26 '15 13:04

Tiddo


People also ask

What does the dot mean in Haskell?

The dot ( . ) is the Haskell operator for function composition. Function composition comes from mathematics but actually, it can be really useful to make music. Haskell was originally designed by mathematicians and computer magicians.

Is Haskell left or right associative?

Haskell also has a binary operator called $ . f $ x does function application just like f x , but it is right-associative, which means you can write f $ g $ h $ x to mean f(g(h(x))) . If you used Haskell enough, you might have once wondered, "would it be nice if f x itself were right-associative?"

How do I use the dot operator in Haskell?

Dot operator in Haskell is completely similar to mathematics composition: f{g(x)} where g() is a function and its output used as an input of another function, that is, f(). The result of . (dot) operator is another function (or lambada) that you can use and call it.

What does the period do in Haskell?

In other words, the period is used to take the result from the function on the right, feed it as a parameter to the function on the left, and return a new function that represents this computation."


1 Answers

First of all, there's a mistake in your [original, unedited] question:

h = f . g is equivalent to h x = g(f x)

— that's not true: h = f . g is equivalent to h x = f (g x).

However, as to why it's that way and not the other way around, it's most likely because that's how it works and has worked in math; see http://en.wikipedia.org/wiki/Function_composition:

[...] composite function is denoted g ∘ f : X → Z, defined by (g ∘ f )(x) = g(f(x)) for all x in X.

It's also intuitive because of the equality (f . g) x == f (g x) — as you can see, the order of f and g is the same on both sides.


Moreover, it's trivial to create your own "reverse composition" operator if you desire one for reasons of e.g. readability:

(.>) = flip (.)

so that

Prelude> ((+1) .> (*2)) 3
8
Prelude> ((+1) . (*2)) 3
7

In fact, you can just use Control.Arrow.(>>>) which does the same for functions but is more general and works for other things as well:

Prelude Control.Arrow> ((+1) >>> (*2)) 3
8
like image 72
Erik Kaplun Avatar answered Sep 19 '22 15:09

Erik Kaplun