haskell - 多重列表理解 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'..]
解决方案
根据您的评论,这些列表例如:
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"]]
推荐阅读
- javascript - Azure 地图示例
- python - 当差异很小时,Python Datetime Time Difference 以分钟为单位给出 -999999999
- django - 自 Django 更新以来,模板渲染抛出“'int' object has no attribute 'encode'”
- java - 我试图运行该应用程序,但它因所需的 bean 而失败
- r - 如何获得 glm 系数的阴影置信区间带?
- android - 导航抽屉滞后,图像
- java - Java 11 编译器无法识别 main 方法中的静态 BiFunction
- mongodb - 如何在 Mongodb 中使用聚合在响应的输出上创建一个数组
- python - 获取 404 的 js 文件
- java - 将文件放在 JAR 的根目录下