首页 > 解决方案 > 多重列表理解 Haskell

问题描述

我正在尝试使用 zipWith (++) 连接两个列表,但出现错误,因为列表 list1 是 [[String]] 而列表 list2 是 [[Char]]。

   temp (n:ns) = n : temp (ns)
   list1 = [ take 10 (repeat (show(n))) | n <- temp ['AA'..]]  
   list2 = infinite list of ['word'...] 

list1 示例 =[['AA', 'AA', 'AA'..], ['BB', 'BB'..]]

list2 示例 =['Word', 'Other', 'Diff', 'New']

如何将 A 与 B 结合起来,以便将 A 的每个项目应用于 B1,然后应用于 B2,...?所以应该是['WordAA', 'OtherAA'..], ['WordBB', 'OtherBB'..]

标签: haskelllist-comprehension

解决方案


根据您的评论,这些列表例如:

b = [["random", "random", "random"], ["eggs", "eggs", "eggs"], ["bacon", "bacon", "bacon"]]
a = ["hello", "hi", "howdy"]

并且您想在 的子列表中b添加相应的字符串a。我们可以使用 和 的组合来做到这map一点zipWith

prepending :: [[a]] -> [[[a]]] -> [[[a]]]
prepending = map . zipWith (++)

这是缩写:

prepending :: [[a]] -> [[[a]]] -> [[[a]]]
prepending a b = map (zipWith (++) a) b

例如:

Prelude> prepending ["hello", "hi", "howdy"] [["random", "random", "random"], ["eggs", "eggs", "eggs"], ["bacon", "bacon", "bacon"]]
[["hellorandom","hirandom","howdyrandom"],["helloeggs","hieggs","howdyeggs"],["hellobacon","hibacon","howdybacon"]]

但是,如果b只是一个字符串列表,例如["random", "eggs", "bacon"],您可以使用两个映射:

prepending :: [[a]] -> [[a]] -> [[[a]]]
prepending a b = map ((`map` b) . (++)) a

然后产生:

Prelude> prepending ["hello", "hi", "howdy"] ["random", "eggs", "bacon"]
[["hellorandom","helloeggs","hellobacon"],["hirandom","hieggs","hibacon"],["howdyrandom","howdyeggs","howdybacon"]]

推荐阅读