list - 如何将列表压缩到嵌套在 Haskell 中的另一个列表上?
问题描述
所以,这是一个类型定义,仅用于某些上下文:
type Name = String
type Coordinates = (Int, Int)
type Pop = Int
type TotalPop = [Pop]
type City = (Name, (Coordinates, TotalPop))
这是一个数据集:
testData :: [City]
testData = [("New York City", ((1,1), [5, 4, 3, 2])),
("Washingotn DC", ((3,3), [3, 2, 1, 1])),
("Los Angeles", ((2,2), [7, 7, 7, 5]))]
所以,我正在尝试制作一个函数 ( addAllPops
) 来编辑TotalPop
所有City
's in [City]
,并在TotalPop
. 我希望它以这样的方式工作,在下面的示例中,输入addNewPop testData [6, 4, 8]
会将它们更改为:
"New York City", ((1,1), [6, 5, 4, 3, 2],
"Washingotn DC", ((3,3), [4, 3, 2, 1, 1],
"Los Angeles", ((2,2), [8, 7, 7, 7, 5]
只改变一个城市人口的功能就在这里,连同我对整体的尝试,我最大的问题完全是将两个列表合并为一个。
addAllPops :: [City] -> [Int] -> [City]
addAllPops [(w, ((x,y), z))] pops = [map uncurry addPop (zip pops z)]
addPop :: City -> Int -> City
addPop (w, ((x,y), z)) p = (w, ((x,y), p:z))
我已经被困在这个问题上很长一段时间了,非常感谢任何和所有的帮助:)
解决方案
您一次开始addPop
工作的直觉是正确的。现在看看 的类型签名zipWith
:
zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
它采用一个逐点操作的函数,并将其提升为并行操作两个列表。所以你zipWith
的城市和新元素列表,使用addPop
逐点组合它们:
addAllPops :: [City] -> [Int] -> [City]
addAllPops cities newPops = zipWith addPop cities newPops
我们可以对这个定义进行 eta-contract 来得出令人惊讶的简单
addAllPops = zipWith addPop
你也可以用zip
and来做这件事map
,但它只是更多的管道。
推荐阅读
- c# - 使用视图模型将数据传递给控制器的问题(两个列表)
- javascript - 在javascript中手机处于静音模式时防止声音
- typescript - Typescript - 数组的映射索引
- php - 模型如何知道它与什么迁移相关联?
- java - 如何调整基线长度
- tensorflow - 时间序列 LSTM 模型错误预测
- react-native - TypeError:null 不是对象(评估 '_firebase.default.auth().currentUser.displayName')
- sql - 有没有办法在 SQL 中将 2 列数据与 1 列配对?
- php - 从 mysql 表中获取数据并在 sql 查询 (PHP) 中的“IN”中使用它们
- google-app-engine - asia.artifacts.../containers/images 中的 appengine 文件可以安全删除吗?