That simple. I want to generate all sublists of a list using list comprehension.
i.e: getSublist [1,2,3] is [[1], [2], [3], [1,2], [1,3], [2, 3], [1,2,3]]
Thanks
As it turns out, you can nest list comprehensions within another list comprehension to further reduce your code and make it easier to read still. As a matter of fact, there's no limit to the number of comprehensions you can nest within each other, which makes it possible to write very complex code in a single line.
A list can contain any sort object, even another list (sublist), which in turn can contain sublists themselves, and so on. This is known as nested list. You can use them to arrange data into hierarchical structures. You can access individual items in a nested list using multiple indexes.
A nested list is a list that appears as an element in another list. In this list, the element with index 3 is a nested list. If we print( nested[3] ), we get [10, 20] .
This is already implemented as Data.List.subsequences
, but if you want to define it yourself (for learning purposes), you can do it like this:
You can't do it with only list comprehensions, but with some recursion it looks like this:
sublists [] = [[]]
sublists (x:xs) = [x:sublist | sublist <- sublists xs] ++ sublists xs
Read: The only sublist of the empty list is the empty list. The sublists of x:xs
(i.e. the list with the head x
and the tail xs
) are all of the sublists of xs
as well as each of the sublists of xs
with x
prepended to them.
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