[Haskell-cafe] Re: Generalizing nested list comprehensions

Heinrich Apfelmus apfelmus at quantentunnel.de
Sat Feb 27 05:04:40 EST 2010


Daniel Fischer wrote:
> Ishaaq Chandy wrote:
>>
>> If this question sounds a bit noob-ish, that would be because I am one -
>> so apologies in advance!
>>
>> I have functions that look something like these:
>>
>> f1 :: [a] -> [b]
>> f1 xs = [foo [x1, x2] |
>>      x1 <- xs,
>>      x2 <- bar x1,
>>      baz x1 /= baz x2]
>>
>> f2 :: [a] -> [b]
>> f2 xs = [foo [x1, x2, x3] |
>>      x1 <- xs,
>>      x2 <- bar x1,
>>      x3 <- bar x2,
>>      baz x1 /= baz x2,
>>      baz x1 /= baz x3,
>>      baz x2 /= baz x3]
>> [...]
>
> Now, there is probably a frighteningly elegant way to do it with foldM or 
> somesuch, but I don't see it at the moment :(

That would be a variant of  iterate  for monads.

    iterateM :: Int -> (a -> m a) -> a -> m [a]
    iterateM n f a
        | n < 0     = return []
        | otherwise = (a:) `liftM` (iterateM (n-1) f =<< f a)


    f n xs = filter p `liftM` (iterateM n bar =<< xs)
        where
        p xs = let ys = map baz xs in nub ys == ys


Regards,
Heinrich Apfelmus

--
http://apfelmus.nfshost.com



More information about the Haskell-Cafe mailing list