什么是函数组合算法,可用于多个参数,如h(x,y)。 f(x)。 g(x)= h(f(x),g(x))? [英] 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))?
问题描述
double(x)= 2 * x
, square(x)= x ^ 2
和 sum(x,y)= x + y
。什么是 compose
,比如 compose(compose(sum,square),double)= x ^ 2 + 2 * x
?注意我正在问一个可以用于任何元素的函数的函数。例如,你可以用 g(x)
,<$ c $来组合 f(x,y,z)
(x),h(x),h(x), i(x)
i(x))。这是一个常见的Haskell成语, applicative functors :
composed = f< $> g1 * g2 * ...< *> gn
(可以找到更好的介绍 here )。
这看起来非常干净,因为有自动部分应用程序,并且像这样工作:
<$ (*)fgx = fx(gx)
(< $>)fgx = f(gx) - 与(。)
相同($) c>
例如,
f < $> g * h *我==>
(\ x - > f(g x))* h *我==>
(\ y - >(\ x - > f(g x))y(h y))*我==>
(\ y→> f(g y)(h y))*我==> (b)(····(g y)(h y))z(i z))==>
(\ z→> f(g z)(h z)(i z))。
尽管如此,应用仿函数更普遍。它们不是一种算法,而是一种概念。例如(如果正确定义的话),您也可以在树上执行相同的操作:
(+)< $> (节点(叶1)(叶2))* (节点(叶子3)(叶子4))==>
Node(Leaf 4)(Leaf 6)
但我怀疑应用程序是否真的可用在大多数其他语言中,由于缺乏简单的部分应用程序。
For example, suppose we had the functions double(x) = 2 * x
, square(x) = x ^ 2
and sum(x,y) = x + y
. What is a function compose
such as compose(compose(sum, square), double) = x^2 + 2*x
? Notice that I'm asking a function that can be used for functions of any arity. For example, you could compose f(x,y,z)
with g(x)
, h(x)
, i(x)
into f(g(x), h(x), i(x))
.
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.
这篇关于什么是函数组合算法,可用于多个参数,如h(x,y)。 f(x)。 g(x)= h(f(x),g(x))?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!