打印具有奇数长度haskell编程的列表的子列表

时间:2017-11-02 22:58:25

标签: haskell

我想打印具有奇数长度的列表的子列表。我编码了这个。

sublists :: [a] -> [[a]]
sublists [] = [[]]
sublists (x:xs) = if odd (length (tail xs))
                  then [x:sublist | sublist <- sublists xs] ++ sublists xs 
                  else sublists xs

例如:sublists [1,2,3,4,5,6]

我的输出为:

[[1,3,5],[1,3],[1,5],[1],[3,5],[3],[5],[]]

我想:

[[1,3,5],[2,3,4],[2,3,5],[1],[2,3,6],[3],[5],[2],[4],[6],[1,2,3],[1,2,4],[1,2,5],[1,2,6],[1,3,4],[1,3,6],[1,4,5],[1,4,6],[1,5,6],[2,4,5],[2,4,6],[2,5,6],[3,4,5],[3,4,6],[3,5,6],[4,5,6],[]]

1 个答案:

答案 0 :(得分:1)

我认为我重复subsequences直到我确定这是瓶颈。特别是因为你似乎很自在地调用了length,所以效率似乎不是一个大问题。所以:

Data.List> filter (odd . length) . subsequences $ [1..4]
[[1],[2],[3],[1,2,3],[4],[1,2,4],[1,3,4],[2,3,4]]