在haskell中具有多值函数的功能组合? [英] Functional composition with multi-valued functions in haskell?
问题描述
我想知道是否可以使用带有多个参数的函数进行函数组合.我希望能够做这样的事情
I was wondering if it was possible to do functional composition with functions that take more than one argument. I want to be able to do something like this
x = (+3).(*)
设置 x 等于一个函数,将两个数字的乘积加三.
setting x equal to a function that adds three to the product of two numbers.
推荐答案
有多种方法可以做到,但都有些别扭.
There are multiple ways to do it, but they're all somewhat awkward.
((+3).) . (*)
≡ fmap (+3) . (*)
≡ curry $ (+3) . uncurry (*)
≡ l r -> l*r + 3
哦,等等,这是签名,还有一个紧凑的定义,猜猜它叫什么...
Oh, wait, this was the signature where there's also a compact definition, guess what it's called...
((.).(.)) (+3) (*)
我认为最明确的 lambda 解决方案在这里是最好的.
I'd argue that the lambda solution, being most explicit, is rather the best here.
什么有帮助,通常只是作为一个(或两个)行在本地完成,是将此组合定义为自定义中缀:
What helps, and is often done just locally as a one(or two)-liner, is to define this composition as a custom infix:
(.:) :: (c->d) -> (a->b->c) -> a->b->d
f .: i = l r -> f $ i l r
它允许您简单地编写 (+3) .: (*)
.
Which allows you to write simply (+3) .: (*)
.
顺便说一句,对于类似的(b->b->c) ->(a->b)->a->a->c
(为中缀的两个参数预先组合正确的函数)存在广泛使用的标准实现.
BTW, for the similar (b->b->c) -> (a->b) -> a->a->c
(precompose the right function to both arguments of the infix) there exists a widely-used standard implementation.
这篇关于在haskell中具有多值函数的功能组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!