What is a function composition algorithm that will work for multiple arguments, such as h(x,y) . f(x) . g(x) = h(f(x),g(x))?

泪湿孤枕 提交于 2019-12-01 13:26:35

This is a common Haskell idiom, applicative functors:

composed = f <$> g1 <*> g2 <*> ... <*> gn

(A nicer introduction can be found here).

This looks very clean because of automatic partial application, and works like this:

(<*>) f g x = f x (g x)
(<$>) f g x = f (g x) -- same as (.)

For example,

f <$> g <*> h <*> i ==>
(\x -> f (g x)) <*> h <*> i ==>
(\y -> (\x -> f (g x)) y (h y)) <*> i ==>
(\y -> f (g y) (h y)) <*> i ==>
(\z -> (\y -> f (g y) (h y)) z (i z)) ==>
(\z -> f (g z) (h z) (i z)).

Applicative functors are more general, though. They are not an "algorithm", but a concept. You could also do the same on a tree, for example (if properly defined):

(+) <$> (Node (Leaf 1) (Leaf 2)) <*> (Node (Leaf 3) (Leaf 4)) ==>
Node (Leaf 4) (Leaf 6)

But I doubt that applicatives are really usable in most other languages, due to the lack of easy partial application.

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