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

Daniel Fischer daniel.is.fischer at web.de
Wed Nov 10 10:37:08 EST 2010


On Wednesday 10 November 2010 16:13:39, David Virebayre 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.
>
> Another wayOne way to do it, although not shorter :
>
> list3 = catMaybes $ zipWith (\a b -> if a > 0 then Nothing else Just
> b) list1 list2

The function you zip with is

\a b -> guard (a /= 0) >> return b,

pointfree: (. return) . (>>) . guard . (/= 0)

using the MonadPlus instance of Maybe. One could use any MonadPlus with a 
function [m a] -> [a] removing the mzeros, like catMaybes for Maybe, concat 
for []:

import Control.Monad (guard)

list3 = concat $ zipWith ((. return) . (>>) . guard . (/= 0)) list1 list2

but I wouldn't say that's better than

list3 = map snd . filter ((/= 0) . fst) $ zip list1 list2

It's not shorter anyway.

>
> David.



More information about the Beginners mailing list