Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Implement this Haskell Function?

Tags:

haskell

Unfortunately I am unable to implement this function I have tried a lot.

f5 :: (Either a b -> c) -> (a -> c, b -> c)

I tried this

f5 k _ (Left x)     =  k x
f5 _ u (Right y)    =  u y

Thanks the help in advance .

like image 778
DanyJ Avatar asked Sep 20 '26 23:09

DanyJ


2 Answers

You implemented

f5 :: (a -> c) -> (b -> c) -> Either a b -> c

You need to do the opposite operation.

f5 :: (Either a b -> c) -> (a -> c, b -> c)
f5 f = (f . Left, f . Right)
like image 61
4castle Avatar answered Sep 24 '26 06:09

4castle


Let the types be your guide.

Your function should take one argument, a function of type Either a b -> c, and produce a pair of functions, (a -> c, b -> c).

(The function you wrote takes three arguments and doesn't produce a pair.)

That is, you want

f5 f = (a_to_c, b_to_c)

where f :: Either a b -> c, a_to_c :: a -> c and b_to_c :: b -> c.

In order to create a_to_c, assume that you have an a and a function Either a b -> c.
Now, there's (only) one way you can make a function of type a -> c from those two things – create an Either from the a with Left, and then pass it to the "Either function".

Informally,

a_to_c x = f (Left x)

or

a_to_c = f . Left

The same reasoning for b leads to a similar situation with b.

b_to_c x = f (Right x)

or

b_to_c = f . Right

Putting them together

f5 f = (f . Left, f . Right)

or, more verbosely

f5 f = (\x -> f (Left x), \x -> f (Right x))
like image 40
molbdnilo Avatar answered Sep 24 '26 06:09

molbdnilo



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!