[Haskell-beginners] best way to code this

briand at aracnet.com briand at aracnet.com
Sun May 31 01:30:44 UTC 2015


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


More information about the Beginners mailing list