Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell notation for composing two functions f and g where g takes multiple arguments

Often I find I want to compose two functions f and g, but g takes multiple arguments. Does Haskell provide a set of operators for that (I know I could write it myself, but it seems fairly common and I don't want to duplicate an operator that already exists in Haskell)

ie something like

(.@) = (.)
(.@@) f g x1 x2 = f $ g x1 x2
(.@@@) f g x1 x2 x3 = f $ g x1 x2 x3
(.@@@@) f g x1 x2 x3 x4 = f $ g x1 x2 x3 x4
...

up to some reasonable number of arguments

like image 502
dspyz Avatar asked May 14 '14 19:05

dspyz


2 Answers

I know you got the answer you wanted, but I wanted to point out that these combinators have the following cute implementation:

(.:)   = (.) . (.)
(.:.)  = (.) . (.) . (.)
(.::)  = (.) . (.) . (.) . (.)
(.::.) = (.) . (.) . (.) . (.) . (.)

and if you only need them fully applied:

f .: g   = (f .) . g
f .:. g  = ((f .) .) . g
f .:: g  = (((f .) .) .) . g
f .::. g = ((((f .) .) .) .) . g

It doesn't seem so terrible to use these expressions directly, without defining an operator. At least the first one, (f .) . g, seems readable enough to me.

like image 53
Omar Antolín-Camarena Avatar answered Oct 17 '22 06:10

Omar Antolín-Camarena


From @bheklilr 's comment, the answer I was looking for is in the composition library: http://hackage.haskell.org/package/composition-1.0.1.0/docs/Data-Composition.html

The functions (.:), (.:.), (.::), (.::.) etc. do exactly what I was thinking

like image 23
dspyz Avatar answered Oct 17 '22 06:10

dspyz