把"map f(map g xs)"写成你可以写的地图的单个调用
示例xs = map(fg)xs
但是如何将"过滤器p(过滤器q xs)"写成过滤器的单个调用?点运算符似乎不适用于过滤器,就像它对地图一样.猜猜你会用其他东西作谓词吗?
如果您定义了一个如下所示的函数both
:
both :: (a -> Bool) -> (a -> Bool) -> a -> Bool
both f g x = f x && g x
Run Code Online (Sandbox Code Playgroud)
然后你可以写:
example xs = filter (both p q) xs
Run Code Online (Sandbox Code Playgroud)
我不确定是否有一个标准功能为你做这个...
$ ghci Prelude> :m +Control.Arrow Prelude Control.Arrow> :t uncurry (&&) . ((0 <) &&& (< 10)) uncurry (&&) . ((0 <) &&& (< 10)) :: (Num a, Ord a) => a -> Bool Prelude Control.Arrow> filter (uncurry (&&) . ((0 <) &&& (< 10))) [0..15] [1,2,3,4,5,6,7,8,9]
或者声明自己的运营商,如果你经常这样做的话.
infixr 3 &&:
p &&: q = \a -> p a && q a
infixr 2 ||:
p ||: q = \a -> p a || q a
not' = (.) not
all' = foldr (&&:) $ const True
any' = foldr (||:) $ const False
example xs = filter (p &&: q ||: not' r) xs
Run Code Online (Sandbox Code Playgroud)
为什么不进行列表理解?
example = [x | x <- xs, p x, q x]
-- for example
example = [x | x <- [1..10], (>3) x, x<5 ] -- [4]
Run Code Online (Sandbox Code Playgroud)