[Haskell-beginners] Selecting single result of function application to list

Michael Xavier nemesisdesign at gmail.com
Thu Nov 3 17:26:40 CET 2011


Here's how I'd do it:

import Data.Maybe (catMaybes)

list = ["hi", "blah", "foo"]

firstJust = head . catMaybes

selectOne f = firstJust . map f

myFunction :: String -> Maybe Int
myFunction = undefined

main = print $ selectOne myFunction list

catMaybes will take a list of Maybe a and reduce it to a list of a,
throwing out all the Nothings.

As you'll learn from working with Maybe a lot, if you're casing off of a
maybe value, there's probably a better way to do it. Functions like
"catMaybes" and "maybe" and especially the Monad instance of Maybe are
really helpful for avoiding this ugly branching logic.

On Thu, Nov 3, 2011 at 9:07 AM, Hugo Ferreira <hmf at inescporto.pt> wrote:
>
>
> I am considering something like:
>
> selectOne f = take 1 . filter (\e -> case e of
>                                       Just _ -> True
>                                       _ -> False ) . map f
>


-- 
Michael Xavier
http://www.michaelxavier.net
LinkedIn <http://www.linkedin.com/pub/michael-xavier/13/b02/a26>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20111103/30b5a8d3/attachment.htm>


More information about the Beginners mailing list