Functional composition with multi-valued functions in haskell?

谁说我不能喝 提交于 2019-11-26 21:47:20

问题


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).(*)

setting x equal to a function that adds three to the product of two numbers.


回答1:


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) (*)

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

Which allows you to write simply (+3) .: (*).

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.




回答2:


Yes, I'd use something like this:

http://hackage.haskell.org/packages/archive/composition/latest/doc/html/Data-Composition.html




回答3:


You could also use the B1 or blackbird combinator from Data.Aviary.Birds. I think for real work I'd use a lambda though.



来源:https://stackoverflow.com/questions/16888222/functional-composition-with-multi-valued-functions-in-haskell

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