我必须编写一个函数,它用一个结果为True
的参数过滤,然后用另一个结果为False
的参数过滤
我试过这个:
selectUnless :: (t -> Bool) -> (t -> Bool) -> [t] -> [t]
selectUnless fx gx (x:xs) = filter gx (filter fx (x:xs))
但我需要那个“不是gx”的列表。
例如:
selectUnless (>= 2) (==2) [1,2,3,4] == [3,4]
selectUnless even odd [1..50] == [2,4..50]
发布于 2019-05-23 04:17:43
因为filter f . filter g = filter (\x -> f x && g x)
,我们只需要一些方法来反转g
。正如Willem提到的那样,它以not
的形式存在。所以我们有:
selectUnless f g = filter (\x -> f x && not (g x))
如果你想变得更聪明一点,你可以提升&&
(<&&>) = liftA2 (&&)
infixr 3 <&&>
selectUnless f g = filter (f <&&> not . g)
您甚至可能会认为这是简洁和意图-揭示了足够的不需要自己的名称。
https://stackoverflow.com/questions/56264267
复制相似问题