创建一个累积列表部分的程序 - Haskell

Creating a program that accumulates parts of a list - Haskell

我正在开发一个程序,它将获取一个三元组列表,并根据其中一个为真,我想求出该三元组其他部分之一的总和。

totalWeightOfFirstClass :: [Parcel] -> Weight
totalWeightOfFirstClass [] = go
totalWeightOfFirstClass ((weight, postcode, firstclass):xs) =
  if firstclass == True then
    go weight
    totalWeightOfFirstClass xs
  else
    totalWeightOfFirstClass xs
where
  go :: Int -> Int
  go _ = 0
  go x =

所以程序应该将列表中的所有权重值相加,并且只有当那个三元组是第一个时才在最后显示它class。到目前为止,我有一个辅助语句,我想累积所有值并最终显示在最后。

如有任何帮助或建议,我们将不胜感激。

问候,基兰。

如果我没理解错的话,你想要先寄出包裹的重量总和class,这应该可以解决问题:

totalWeightOfFirstClass :: [Parcel] -> Weight
totalWeightOfFirstClass [] = 0
totalWeightOfFirstClass ((weight, postcode, firstclass):xs)
    | firstclass = weight + totalWeightOfFirstClass xs
    | otherwise = totalWeightOfFirstClass xs

你的代码工作量太大了。尝试考虑使用通用组合器来表达您的代码,而不是像这样编写原始递归。

totalWeightOfFirstClass = sum . (fmap (\(weight, _, _) -> weight)) . filter (\(_, _, firstc) -> firstc)

它在应用过滤器后对所有权重求和。如您所见,代码非常清晰易读。