[Haskell-beginners] best way to code this

Chaddaï Fouché chaddai.fouche at gmail.com
Sun May 31 09:47:50 UTC 2015


Note that all proposed solutions are in O(n²) while this can be realized in
O(n log n) (sort both list then match them in order). It depends on your
use case if this is worthwhile.

-- 
Jedaï

Le dim. 31 mai 2015 à 07:17, Alex Hammel <ahammel87 at gmail.com> a écrit :

> f as alist = [ b | (a, b) <- alist, a `elem` as ]
>
> perhaps?
>
> On Sat, 30 May 2015 6:47 pm Lyndon Maydwell <maydwell at gmail.com> wrote:
>
>> 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
>>>
>>
>> _______________________________________________
>> Beginners mailing list
>> Beginners at haskell.org
>> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
>>
> _______________________________________________
> 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/74c94103/attachment.html>


More information about the Beginners mailing list