【问题标题】:Haskell - combinations of lists and finding the maximum number of itemsHaskell - 列表组合和查找最大项目数
【发布时间】:2020-10-26 11:41:03
【问题描述】:

假设我有一个如下所示的列表:

ls = [[a, b, c, d, e], [a, b, c, d], [a, c, e]]

此列表列表中的每个列表都属于自定义数据类型(就排序列表而言,这可能很重要,所以我将其输入):

data Custom = Custom String Int

我想在这个列表列表中获得 1-3 个列表的所有可能组合,并找到给我最多唯一项的组合。输出应该是这样的(格式化以便于阅读):

ms = [
[[a, b, c, d, e]], 
[[a, b, c, d]], 
[[a, c, e]], 
[[a, b, c, d, e], [a, b, c, d]], 
[[a, b, c, d, e], [a, c, e]],
[[a, b, c, d], [a, c, e]],
[[a, b, c, d, e], [a, b, c, d], [a, c, e]]
]

这样我就可以映射一个函数来计算列表列表中的唯一项目,以找到给我最大数量的唯一项目的列表列表。

但是在使用这些功能时:

listOfListCombo :: Int -> [[a]] -> [[[a]]]
listOfListCombo _ [] = []
listOfListCombo n (x : xs) = map (x :) (listOfListCombo (n - 1) xs) ++ listOfListCombo n xs

combos :: [[Custom]] -> [[[Custom]]]
combos xs = (listOfListCombo 1 xs) ++ (listOfListCombo 2 xs) ++ (listOfListCombo 3 xs)

我在调用combos xs 时总是得到一个空列表。请注意,调用listOfListCombo n xs 也会给我一个空列表,所以我怀疑问题出在那儿。

我应该如何从列表列表中生成列表列表,以便我可以使用它来找到理想的组合?

【问题讨论】:

    标签: haskell


    【解决方案1】:

    已经有一个内置函数:Data.List.subsequences :: [a] -> [[a]]。实现非常简单:

    subsequences :: [a] -> [[a]]
    subsequences xs = [] : nonEmptySubsequences xs
    
    nonEmptySubsequences :: [a] -> [[a]]
    nonEmptySubsequences [] = []
    nonEmptySubsequences (x:xs) =
       [x] : foldr (\ys r -> ys : (x : ys) : r) [] (nonEmptySubsequences xs)
    

    但如果你想炫耀你的monad-monkey精神,你总是可以filterM (const [True, False])

    【讨论】:

    • 我还导入了Data.List,所以我想我可以使用subsequences。谢谢。
    • 如果这解决了您的问题,您可以将其标记为已解决
    猜你喜欢
    • 1970-01-01
    • 2015-09-29
    • 2013-01-11
    • 2019-04-03
    • 2018-09-13
    • 1970-01-01
    • 2012-05-17
    • 2022-11-21
    • 1970-01-01
    相关资源
    最近更新 更多