Sublists of a list using list comprehension

后端 未结 1 1062
Happy的楠姐
Happy的楠姐 2021-01-12 17:09

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

Th

相关标签:
1条回答
  • 2021-01-12 17:45

    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.

    0 讨论(0)
提交回复
热议问题