将函数组合成另一个函数

时间:2016-05-27 17:09:12

标签: haskell functional-programming higher-order-functions

标准库中是否有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

2 个答案:

答案 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