1
A
回答
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]
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]
7
表達多個過濾器條件的好方法是理解,例如
[k | k <- [1..10], k > 2, k < 7]
可以避免λ表達式作爲使用公Applicative
,其允許「喂」一個參數到幾個功能:
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]
什麼,你會期望在該表格的價值? – 2011-06-08 09:16:00