[Haskell-beginners] How to select items from one list depending on another

Magnus Therning magnus at therning.org
Wed Nov 10 11:11:19 EST 2010


On Wed, Nov 10, 2010 at 16:08, Alexey Levan <exlevan at gmail.com> wrote:
> 2010/11/10 C K Kashyap <ckkashyap at gmail.com>:
>> Hi,
>> I have this problem at hand -
>>
>> Given two lists
>>
>> list1 = [0,1,2,0,1,4]
>>
>> list2 = [1,2,3,4,5,6]
>>
>> I need to take items from the second list only when the corresponding
>> item in list1 is non-zero.
>>
>> list3 = map snd $ filter takeValid $ zip list1 list2 where
>>                       takeValid (a,b) = a /= 0
>>
>> Is there a shorter way?
>
> You can use list comprehenison and pattern matching here:
>
> list3 = [xs | (0, xs) <- zip list1 list2]

Or, since the OP asked for the "opposite":

[b | (a, b) <- zip list1 list2, a /=0 ]

/M

-- 
Magnus Therning                        (OpenPGP: 0xAB4DFBA4)
magnus@therning.org          Jabber: magnus@therning.org
http://therning.org/magnus         identi.ca|twitter: magthe


More information about the Beginners mailing list