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

Chaddaï Fouché chaddai.fouche at gmail.com
Tue Jul 23 21:12:51 CEST 2013


Le 23 juil. 2013 10:54, "Costello, Roger L." <costello at mitre.org> a écrit :
>
> 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?

This is pretty normal since there are no elements in "g xs" so b can takes
no values. You have got some excellent answers on that but I think your
problem is more fundamental :

> f x = x

This function does nothing or more precisely it is the identity, you can
replace "f anything" by "anything" and have exactly the same result.

> g x = []

This function just takes anything and returns an empty list. So

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

Is exactly the same as :

> [(a,b) | a <- xs, b <- [] ]

If xs is ["a"] that becomes

> [(a,b) | a <- ["a"], b <- [] ]

I think those f and g didn't work like that in your mind so could you
explain what you thought they should do (with some examples maybe).

-- 
Jedaï
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20130723/0515b03e/attachment.htm>


More information about the Beginners mailing list