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

Hugo Ferreira hmf at inescporto.pt
Thu Nov 3 17:33:15 CET 2011


On 11/03/2011 04:26 PM, Michael Xavier wrote:
> 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.
>

Thanks Michael. I am planning to compose functions that return Maybe
so I will, as you pointed out, be looking at the Maybe Monad.

Rgards,
Hugo F.

> On Thu, Nov 3, 2011 at 9:07 AM, Hugo Ferreira <hmf at inescporto.pt
> <mailto: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>
>




More information about the Beginners mailing list