[Haskell-beginners] Why does this list comprehension return an empty list?

Costello, Roger L. costello at mitre.org
Tue Jul 23 10:53:28 CEST 2013


Hi Folks,

I have a list of singletons:

	xs = [("a")]

f is a function that, given an argument x, it returns the argument:

	f x = x

g is a function that, given an argument x, it returns the empty list:

	g x = []

I have a list comprehension that extracts the singletons from xs using f and g, and creates a pair from their output:

	[(a,b) | a <- f xs, b <- g xs]

I executed this and the result is the empty list:

	[]

That is odd. Why is the empty list the result?

Consider this list comprehension that extracts the singletons from xs using f only, and creates a pair by matching up the singleton from xs with the empty list:

	[(a,[]) | a <- f xs]

The result is this:

	[("a",[])]

That is the result that I expected to get with the first list comprehension. 

Would you explain why this:

	[(a,b) | a <- f xs, b <- g xs]

yields [], whereas this:

	[(a,[]) | a <- f xs]

yields [("a",[])]?

Also, how would I modify this:

	[(a,b) | a <- f xs, b <- g xs]

so that it produces this:

	[("a",[])]

/Roger




More information about the Beginners mailing list