[Haskell-beginners] List comprehensions with multiple generators

Francesco Ariis fa-ml at ariis.it
Sun Apr 26 13:39:13 UTC 2020

Hello Ken,

On Sun, Apr 26, 2020 at 08:50:20AM -0400, Ken Overton wrote:
> I recently came across this function which made me realize I don't
> understand list comprehensions well. I hope someone can help me understand
> them better by understanding this example better. The function takes a list
> of Eq and returns the list of unique elements from it:
>     unique :: Eq a => [a] -> [a]
>     unique xs = [x | (x,y) <- zip xs [0..], x `notElem` (take y xs)]
> [...]
> So the first generator should produce [(Eq,Int)] as input to the second
> generator? And the second generator should produce [Bool]?

1. (x,y) <- zip xs [0..] -- generates a list of pairs.
2. x `notElem` (take y xs) -- acts like a guard to 1., so only the `x`s
   which are not in the first `y` elements of `xs` (in other words, the
   previous elements of `xs`) will be returned.

The examples on the wiki [1] show more way of using list

[1] https://wiki.haskell.org/List_comprehension#Examples

More information about the Beginners mailing list