首页 > 解决方案 > 如何将列表压缩到嵌套在 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))

我已经被困在这个问题上很长一段时间了,非常感谢任何和所有的帮助:)

标签: listhaskellnested-listsmap-functionalgebraic-data-types

解决方案


您一次开始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

你也可以用zipand来做这件事map,但它只是更多的管道。


推荐阅读