Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell- composing three functions in weird way

I have three functions x y z and a function called functionComposer.

I want functionComposer to have as arguments the functions x y z and to return me a function that uses the result of y and z as arguments into x and applies x.

In mathematical notation: x(y(a),z(b))

Im NOT asking for this : functionComposer x y z = x.y.z

For example:

double x = x + x

summer x y = x + y

functionComposer summer double double = summer (double) (double) 

if x = 2 the result should be 8 (2+2)+(2+2)

like image 847
user3630355 Avatar asked Feb 05 '26 01:02

user3630355


2 Answers

You can also use the applicative instance for (->) a like so

import Control.Applicative


funcComp summer double1 double2 = summer <$> double1 <*> double2

Or the monad instance

funcComp summer double1 double2 = liftM2 summer double1 double2

The way to understand this is that for (->) a, both the applicative and the monad instance are meant to "parametrize" over the function value that double1 and double2 both accept.

like image 54
Daniel Gratzer Avatar answered Feb 09 '26 01:02

Daniel Gratzer


Using your notation:

functionComposer summer double1 double2 = \x -> summer (double1 x) (double2 x) 

The \x -> ... represents the function mapping x to the ....

Note I had to give different names to the double function argument, since in general you want to compose different functions.

like image 41
chi Avatar answered Feb 09 '26 02:02

chi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!