Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell idiom for 'selective' map

Tags:

haskell

map

Suppose one wants to map over a collection, but only collect results of the mapped function if the mapped-upon value meets certain criteria. I am currently doing this as such:

func = foldl (\acc x, ->  (maybeGrab x):acc) []


maybeGrab a
    | a > 5 = [someFunc a]
    | otherwise = []

While this works, I am sure there is a more idiomatic 'right/common/more recognisable' way to do this.

like image 518
providence Avatar asked Oct 23 '11 19:10

providence


2 Answers

 mapMaybe :: (a -> Maybe b) -> [a] -> [b]

mapMaybe from the Data.Maybe package looks like it does the job. The documentation says:

The mapMaybe function is a version of map which can throw out elements. In particular, the functional argument returns something of type Maybe b. If this is Nothing, no element is added on to the result list. If it just Just b, then b is included in the result list.

like image 51
Jeff Foster Avatar answered Sep 22 '22 13:09

Jeff Foster


Personally, I would do this in two stages: first, eliminate the values you don't care about, then map.

func = map someFunc . filter (>5)

This can also be expressed nicely as a list comprehension.

func xs = [someFunc x | x <- xs, x > 5]
like image 28
Daniel Wagner Avatar answered Sep 21 '22 13:09

Daniel Wagner