是否可以在地图功能中使用条件?
例如:
map (> 0 < 100 )[1..10]
如果不可能,怎么能实现这个目标呢?
答案 0 :(得分:7)
表达多个过滤条件的好方法是理解,例如:
[k | k <- [1..10], k > 2, k < 7]
你可以使用Applicative
来避免lambda表达式,它允许将一个参数“提供”给几个函数:
import Control.Applicative
filter ((&&) <$> (>2) <*> (<7)) [1..10]
这可以通过以下轻微的神秘方式扩展到多个测试:
import Control.Applicative
filter (and . ([ (>2) , (<7) , odd ] <*>) . pure) [1..10]
当然,在过滤后,您可以以任何您喜欢的方式映射列表。
<强> [编辑] 强>
如果你想炫耀,你也可以使用箭头:
import Control.Arrow
filter ((>2) &&& (<7) >>> uncurry (&&)) [1..10]
答案 1 :(得分:5)
不完全相同,我假设您正在尝试获取一个布尔值,指示该值是否大于0且小于100?您有几种选择:
您可以命名一个功能
condition :: Int -> Bool
condition x = x > 0 && x < 100
map condition [1..10]
您可以使用lambda
map (\x -> x > 0 && x < 100) [1..10]
您可以使用Data.Ix
和inRange
功能
import Data.Ix
-- inRange is inclusive.
map (inRange (1,99)) [1..10]
答案 2 :(得分:5)
map
用于在列表上映射函数。如果您只想在满足条件的列表元素上映射函数,那么您应该使用filter
:
map (+2) $ filter (>0) [-10..120]
或者如果您有更多必须持有的条件
map (+2) $ filter (>0) $ filter (<100) [-10..120]
或等效
map (+2) $ filter (\x -> x>0 && x<100) [-10..120]