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

你说的曾经没有我的故事 提交于 2019-12-21 12:12:03

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/29878545/why-does-the-dot-compose-from-right-to-left-in-haskell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!