标准库中是否有Haskell函数,该函数接受三个函数并返回一个函数,该函数将前两个函数的返回值应用于第三个函数,如下所示:
compact :: (a -> b) -> (a -> c) -> (b -> c -> d) -> a -> d
compact a b c = \x -> c (a x) (b x)
或者这个:
import Control.Arrow
compact' :: (a -> b) -> (a -> c) -> (b -> c -> d) -> a -> d
compact' a b c = uncurry c . (a &&& b)
那样:
compact (take 1) (drop 2) (++) [1,2,3,4] == [1,3,4]
compact (+10) (*2) (<) 11 == True
compact (+10) (*2) (<) 9 == False
答案 0 :(得分:5)
如果您将签名重新排序为:
(b -> c -> d) -> (a -> b) -> (a -> c) -> a -> d
这相当于liftM2
,因为((->) r)
is an instance of Monad type class
liftM2 :: Monad m => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r
和
\> liftM2 (++) (take 1) (drop 2) [1, 2, 3, 4]
[1,3,4]
类似地,来自Control.Applicative
的{{3}}:
liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c
\> liftA2 (++) (take 1) (drop 2) [1, 2, 3, 4]
[1,3,4]
答案 1 :(得分:4)
liftM2
的 Control.Monad
几乎与您的compact
函数相同,只是参数的顺序不同。
liftM2 :: Monad m => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r
在上下文中与:
相同 liftM2 :: (b -> c -> d) -> (a -> b) -> (a -> c) -> a -> d
所以:
liftM2 (++) (take 1) (drop 2) [1,2,3,4] == [1,3,4]
liftM2 (<) (+10) (*2) 11 == True
liftM2 (<) (+10) (*2) 9 == False