Haskell如何将列表与嵌套列表配对以批量更新City类型的TotalPop字段
解决方案
你已经正确实现了单条城市人口更新的addPop函数,仅需用zipWith完成两个列表的按位配对调用即可,完整实现如下:
addAllPops :: [City] -> [Int] -> [City] addAllPops = zipWith addPop addPop :: City -> Int -> City addPop (name, (coords, history)) newPop = (name, (coords, newPop : history))
说明
zipWith接收二元函数、两个等长列表作为参数,会按索引依次从两个列表中各取一个元素传入函数,最终把所有返回值组装成新列表,刚好匹配需求:第n个城市对应第n个新增人口值,逐个调用addPop完成更新。
你也可以写成显式带参数的形式方便理解:
addAllPops cities newPops = zipWith addPop cities newPops
你原有代码的问题在于:
- 模式匹配只覆盖了单元素城市列表的情况,无法处理任意长度的输入
- 配对逻辑错误,你不需要将新增人口列表和单城市的历史人口列表配对,而是要和整个城市列表按索引配对
测试效果
调用addAllPops 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])) ]
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

