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?
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.
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.
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.
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.
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 Int
s 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With