Evg
Evg

Reputation: 3080

haskell style generalized function composition

we have some different types

Prelude> type T1 = Int
Prelude> type T2 = Int
Prelude> type T3 = Int
Prelude> type T4 = Int
...
Prelude> type X1 = Int
Prelude> type X2 = Int
Prelude> type X3 = Int
Prelude> type X4 = Int

and some functions

Prelude> let f1 :: X1->T1; f1 = (+1)
Prelude> let f2 :: X2->T2; f2 = (+2)
Prelude> let f3 :: X3->T3; f3 = (+3)
...
let g :: T1 -> T2 -> T3; g = (+)

and I want build some new functions, for ex:

c :: X1 -> X2 -> T3
c x1 x2 = g (f1 x1) (f2 x2)

but what if I want to define new function more like composition way without explicitly working with arguments

Prelude> nc =  flip ((flip (g.f1)).f2)

now nc works as c

but with flip I can do it only to N=2 arguments, i stacked for N=3:

Prelude> let g3 :: T1->T2->T3->T4; g3 t1 t2 t3 = t1+t2+t3

Prelude> :t (flip ((flip (g3.f1)).f2))
(flip ((flip (g3.f1)).f2)) :: X1 -> X2 -> T3 -> T4
Prelude> :t flip (flip ((flip (g3.f1)).f2))
flip (flip ((flip (g3.f1)).f2)) :: X2 -> X1 -> T3 -> T4

how to make T3 first? and with growing N it getting complex, and not readable.

I want to generalize this idea to arbitary N functions.

So I think I need some function what gets on input all that stuff and produce composed function

finally I come with solution to define compositors functions for all N:

Prelude> compose3 = \g f1 f2 f3 x1 x2 x3 -> g (f1 x1) (f2 x2) (f3 x3)
Prelude> compose4 = \g f1 f2 f3 f4 x1 x2 x3 x4 -> g (f1 x1) (f2 x2) (f3 x3) (f4 x4)
... etc

let c3 = compose3 g3 f1 f2 f3
Prelude> :t c3
c3 :: X1 -> X2 -> X3 -> T4
Prelude> c3 1 2 3
12

but it requires to write definition for every N

what is the expressive haskell way to do such composition for abitary N?

I know what there is a Reader monad for specific function composition, but I search for general with different types of input, can Monads do this job?

Also I know little about Arrow typeclass, may be it is applicable here? and if it is, can you please provide example.

Upvotes: 0

Views: 125

Answers (0)

Related Questions