Reputation: 51
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 .
Upvotes: 2
Views: 100
Reputation: 66371
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))
Upvotes: 3
Reputation: 33466
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)
Upvotes: 6