繁体   English   中英

我怎样才能在 zip 的一个列表上覆盖另一个嵌套在 Haskell 中的列表?

[英]How can I zip a list over another list that is nested in 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]))]

因此,我正在尝试制作 function ( addAllPops )来编辑[City]中所有CityTotalPop ,并在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]

function 只改变一个城市的人口就在这里,连同我对整体的尝试,我最大的问题完全是将两个列表合并为一个。

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]

它需要一个 function,它逐点运行并提升它以在两个列表上并行运行。 所以你zipWith城市和新元素列表,使用addPop逐点组合它们:

addAllPops :: [City] -> [Int] -> [City]
addAllPops cities newPops = zipWith addPop cities newPops

我们可以对这个定义进行 eta-contract 来得出令人惊讶的简单

addAllPops = zipWith addPop

您也可以使用zipmap来完成此操作,但这只是更多的管道。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM