将函数组合成另一个函数

Compose functions into another function

标准库中是否有一个函数 Haskell 接受三个函数,return 一个函数将前两个函数的 return 值应用到第三个函数,像这样:

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

如果您将签名重新排序为:

(b -> c -> d) -> (a -> b) -> (a -> c) -> a -> d

这相当于liftM2, since ((->) 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]

类似地,liftA2 来自 Control.Applicative:

liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c

\> liftA2 (++) (take 1) (drop 2) [1, 2, 3, 4]
[1,3,4]
Control.Monad 中的

liftM2 与您的 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