[Haskell-beginners] Why does this list comprehension return an empty list?
Frerich Raabe
raabe at froglogic.com
Tue Jul 23 11:08:10 CEST 2013
On 2013-07-23 10:53, Costello, Roger L. wrote:
> 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 how the list comprehension looks like when written as monadic
code:
f xs >>= \a ->
g xs >>= \b ->
return (a,b)
I.e. "for each element 'a' drawn from the result of "f sx", draw an
element 'b' from the result of "g xs" and yield a new element "(a,b)".
So the resulting list will always be 'length (f xs) * length (g xs)'
items in length. Consequently, if either of the two lists is empty, the
result will be empty.
--
Frerich Raabe - raabe at froglogic.com
www.froglogic.com - Multi-Platform GUI Testing
More information about the Beginners
mailing list