简体   繁体   中英

How to Implement this Haskell Function?

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

f5 :: (Either ab -> 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 .

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)

Let the types be your guide.

Your function should take one argument, a function of type Either ab -> 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 ab -> 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 ab -> 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM