Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need explanation for list comprehension in Haskell

I'm just starting with functional programming and I am learning Haskell programming language. Due to the fact that I am just a beginner, I have a piece of code and I need an explanation about this:

ghci> let xxs = [[1,3,5,2,3,1,2,4,5],[1,2,3,4,5,6,7,8,9],[1,2,4,2,1,6,3,1,3,2,3,6]]
ghci> [ [ x | x <- xs, even x ] | xs <- xxs]
-- Output: 
-- [[2,2,4],[2,4,6,8],[2,4,2,6,2,6]] 

I see this code will produce the new list with the even numbers in each sub-list.

But I don't know why x <- xs and then xs <- xxs, why can't we do x <- xxs in the first place?

like image 591
Nam V. Do Avatar asked Jul 09 '19 07:07

Nam V. Do


People also ask

What is list comprehension explain?

List comprehension is an easy to read, compact, and elegant way of creating a list from any existing iterable object. Basically, it's a simpler way to create a new list from the values in a list you already have. It is generally a single line of code enclosed in square brackets.

Are list comprehensions necessary?

List comprehensions are useful and can help you write elegant code that's easy to read and debug, but they're not the right choice for all circumstances. They might make your code run more slowly or use more memory.

What is the difference between list and list comprehension?

The for loop is a common way to iterate through a list. List comprehension, on the other hand, is a more efficient way to iterate through a list because it requires fewer lines of code. List comprehension requires less computation power than a for loop because it takes up less space and code.

What is the core syntax for a list comprehension?

As per the above syntax, the list comprehension syntax contains three parts: an expression, one or more for loop, and optionally, one or more if conditions. The list comprehension must be in the square brackets [] . The result of the first expression will be stored in the new list.


1 Answers

xss is a list of lists of numbers. Let us assume it has type [[Int]] (the number type can be different, but that does not make any difference).

This means that if we define a generator xs <- xxs, then xs will have the type of the elements of that list, so [Int]. An [Int] is not an Integral type, so we can not check if a list of Ints is even :: Integral a => a -> Bool.

We can however process that sublist xs further. For example with another list comprehension, like [ x | x <- xs, even x ] that filter the sublist.

It might however be more clear what you do with:

[ filter even xs | xs <- xss ]

or we can here convert the outer list comprehension to a simple map:

map (filter even) xss
like image 60
Willem Van Onsem Avatar answered Sep 28 '22 04:09

Willem Van Onsem