如何减少处理Maybe和列表的样板?

时间:2014-07-10 19:03:31

标签: haskell

是否有更简洁的方法来组合生成列表的函数与其他生成Maybe s?

import Text.Feed.Query (getItemLink, getFeedItems)

s = getFeedItems >=> (maybeToList . getItemLink)

1 个答案:

答案 0 :(得分:2)

您可以使用Data.Maybe中的mapMaybe :: (a -> Maybe b) -> [a] -> [b]

s = mapMaybe getItemLink . getFeedItems

该模块还包含另一个有用的功能catMaybes

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

列表推导在这种情况下也很有用,虽然更详细:

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