List 如何更新多个列表中的数据Haskell
。更新最新里程数据列表中的数据, 删除每个位置最早的英里数List 如何更新多个列表中的数据Haskell,list,haskell,List,Haskell,。更新最新里程数据列表中的数据, 删除每个位置最早的英里数 data People= People{ person:: String, age:: Int, weigth:: Float, miles:: [Float]} testData :: [People] testData = [ person "sara" 19 50 [ 5, 8, 8], person "ed" 50 60 [0 , 1, 2], per
data People= People{ person:: String, age:: Int, weigth:: Float, miles:: [Float]}
testData :: [People]
testData = [ person "sara" 19 50 [ 5, 8, 8],
person "ed" 50 60 [0 , 1, 2],
person "norman" 25 75 [ 2, 3 ,5]]
我正在尝试删除所有最后的数字,并将新的数字添加到给定的每个列表中[2,1,5]
因此,我将有[[2,5,8],[1,0,1],[5,2,3]]作为每个人的新里程你可以使用
zipWith::(a->b->c)->[a]->[b]->[c]
。它使用助手函数将两个列表压缩在一起
首先,您需要定义此帮助器,它接受人员
和浮点
,并返回更新的人员
,例如
update :: Float -> People -> People
update n people = people { miles = newMiles }
where newMiles = n : init (miles people)
这可以与zipWith
一起使用,如下所示:
zipWith update [2, 1, 5] testData
请注意,
testData
的定义不正确。您必须使用人员
数据构造函数,如下所示:
testData :: [People]
testData = [ People "sara" 19 50 [5, 8, 8]
-- etc.
]
所以基本上你可以这样做
data People = People { person :: String
, age :: Int
, weight :: Float
, miles :: [Float]
} deriving (Show)
testData :: [People]
testData = [ People "sara" 19 50 [5,8,8]
, People "ed" 50 60 [0,1,2]
, People "norman" 25 75 [2,3,5]
]
addMiles :: [People] -> [Float] -> [People]
addMiles ps ms = zipWith f ps ms
where
f p m = p {miles = m : init (miles p)}
或者你也可以喜欢
addMiles :: [People] -> [Float] -> [People]
addMiles = zipWith (\p m -> p {miles = m : init (miles p)})
然后,
首先格式化代码,以便我们能够理解:/T%hanks对testData定义的更正
addMiles testData [2,1,5]
[ People {person = "sara", age = 19, weight = 50.0, miles = [2.0,5.0,8.0]}
, People {person = "ed", age = 50, weight = 60.0, miles = [1.0,0.0,1.0]}
, People {person = "norman", age = 25, weight = 75.0, miles = [5.0,2.0,3.0]}
]