Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sublists of a list using list comprehension

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

like image 643
atks Avatar asked Mar 01 '11 00:03

atks


People also ask

Can you nest list comprehensions?

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.

Can a list be nested in another list?

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.

What is nested list with example?

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] .


1 Answers

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.

like image 116
sepp2k Avatar answered Oct 15 '22 13:10

sepp2k