多列表理解Haskell

时间:2020-07-15 20:26:34

标签: haskell list-comprehension

我试图用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'...] 

列表1的示例= [['AA', 'AA', 'AA'..], ['BB', 'BB'..]]

列表2的示例= ['Word', 'Other', 'Diff', 'New']

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

1 个答案:

答案 0 :(得分:1)

基于您的comment,列表例如:

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

,并且您要在b的子列表中添加a中相应的字符串。我们可以结合使用mapzipWith

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