[Haskell-beginners] best way to code this

Lyndon Maydwell maydwell at gmail.com
Sun May 31 01:47:01 UTC 2015


I think you're looking for `mapMaybe` :-)


 - Lyndon

On Sun, May 31, 2015 at 11:30 AM, <briand at aracnet.com> wrote:

> Hi,
>
> A simple example of something I was trying to do but it had some questions
> along the lines of "the best way to do this".
>
> Given a list
>
>   l = [a]
>
> and an a-list
>
>   alist = [ (a,b) ]
>
> the idea is to find all the items in l which are in alist and then create
> a list [b]
>
> so the overall function should be
>
>  [a] -> [ (a,b) ] -> [b]
>
> the solution is straightforward:
>
>  l1 = filter (\x -> isJust (lookup x alist)) l
>  l2 = map (\x -> fromJust (lookup x alist)) l1
>
> `fromJust` used in the construction of l2 won't fail, because only the
> elements for which the lookup succeeded are in l1.
>
> This would be something called `filterMap` but I couldn't find such a
> function in the list library, but it seems like there just has to be one
> defined in a library somewhere.
>
> the above seems clumsy, i'm wondering how to make it "more pretty".
>
> generally i was also wondering if the above construction is as inefficient
> as it looks because of the double-lookup, or would the compiler actually be
> able to optimize that code into something more efficient ?  this code is
> not being used on large sets of data so efficiency doesn't matter, I'm just
> curious.
>
> Thanks,
>
> Brian
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20150531/78539146/attachment.html>


More information about the Beginners mailing list