开发者

Haskell condition in a map function

Is it possible to have a condition in a map function?

For example :

map (> 0 < 100 )[1..10]

开发者_JAVA百科If it's not possible, how could one achieve this?


A good way to express multiple filter conditions are for comprehensions, e.g.

[k | k <- [1..10], k > 2, k < 7]

You can avoid the lambda expression as well using Applicative, which allows to "feed" a single argument to several functions:

import Control.Applicative

filter ((&&) <$> (>2) <*> (<7)) [1..10]

This can be extended for multiple tests in the following slighty cryptic way:

import Control.Applicative

filter (and . ([ (>2) , (<7) , odd ] <*>) . pure) [1..10]

Of course after filtering you can map the list in any way you like.

[Edit]

If you want to show off, you can use Arrows as well:

import Control.Arrow

filter ((>2) &&& (<7) >>> uncurry (&&)) [1..10]


Not quite like that, I presume you are trying to get a boolean indicating whether the value is greater than 0 and less than 100? You have several options:

You can name a function

condition :: Int -> Bool
condition x = x > 0 && x < 100
map condition [1..10]

You can use a lambda

map (\x -> x > 0 && x < 100) [1..10]

You can use Data.Ix and the inRange function

import Data.Ix

-- inRange is inclusive.
map (inRange (1,99)) [1..10]


map is used to map a function over a list. If you want to map a function only on the elements of a list that satisfy a condition, then you should probably use filter:

map (+2) $ filter (>0) [-10..120]

or if you have more conditions that must all hold

map (+2) $ filter (>0) $ filter (<100) [-10..120]

or equivalently

map (+2) $ filter (\x -> x>0 && x<100) [-10..120]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜