列表使用列表理解的子列表 [英] Sublists of a list using list comprehension
问题描述
即:getSublist [1,2,3]是[[1],[2],[3 ],[1,2],[1,3],[2,3],[1,2,3]]
谢谢
这已经被实现为 Data.List.subsequences
,但是如果你想要定义它你可以这样做:
你不能仅仅使用列表推导来完成它,但是通过一些递归,它看起来像这样: / p>
sublists [] = [[]]
sublists(x:xs)= [x:sublist |子列表< - 子列表xs] ++子列表xs
阅读:空列表的唯一子列表是空的列表。 x:xs
的子列表(即头部 x
和尾部 xs的列表
)的所有子列表都是
xs
以及每个 xs
x
>。
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
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.
这篇关于列表使用列表理解的子列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!