Rumca
Rumca

Reputation: 1829

How to reduce boilerplate dealing with Maybe and lists?

Is there a cleaner way to compose functions producing lists with other producing Maybes?

import Text.Feed.Query (getItemLink, getFeedItems)

s = getFeedItems >=> (maybeToList . getItemLink)

Upvotes: 3

Views: 195

Answers (1)

bennofs
bennofs

Reputation: 11973

You can use mapMaybe :: (a -> Maybe b) -> [a] -> [b] from Data.Maybe:

s = mapMaybe getItemLink . getFeedItems

That module also contains another useful function, catMaybes:

catMaybes :: [Maybe a] -> [a] -- filter out all the Nothings

List comprehensions are also useful in this case, although more verbose:

s feed = [ itemLink | Just itemLink <- map getItemLink (getFeedItems feed) ]
-- s feed = [ itemLink | item <- getFeedItems feed, Just itemLink <- return item ] 

Upvotes: 2

Related Questions