繁体   English   中英

计算列表中项目的价格

[英]Calculate Price of items in a list

我正在学习 Haskell 中的代数数据类型,但遇到了一个我无法解决的问题。

所以我想输入一份杂货清单,作为输出我应该得到总价。

现在,我有以下类型:

data Item = A | B | C deriving (Eq, Show)
data List = Empty | Add Item List

我有杂货清单: list1 = A `Add` (B `Add` Empty)

我有一个功能(设置物品的价格):

p:: Item -> Int
p A = 2
p B = 4
p C = 5

现在这是我遇到困难的地方。 我想将函数“p”应用于我的 list1。 但我不确定如何。

这是我当前的代码:

price:: (Item -> Int) -> List -> Int
price p (Add x xs)
    | x == A = A + price xs
    | x == B = B + price xs
    | x == C = C + price xs
    | otherwise = 0

我也试过这个。

price:: (Item -> Int) -> List -> Int
price p (Add x xs) = x + price xs

提前致谢!

price的第一个参数是一个接受List参数并返回Int的函数(类似于声明的p函数,但不要将它与price p (Add x xs)模式中的p参数混淆,为了清楚起见,我将前一个参数重命名为c ) ,因此实现可能如下所示:

price :: (Item -> Int) -> List -> Int
price _ Empty = 0 -- match empty List
price c (Add x xs) = (c x) + price c xs -- match non-empty and perform recursive call to price

调用看起来像price p $ Add A Empty (计算一个 A 列表的价格)。

除了 chepner 关于实施mapList的建议之外,我可能还建议编写foldrList

foldrList _ i Empty = i
foldrList f i (Add x xs) = f x (foldrList f i xs)

这样做之后,可以计算出项目列表的总价:

totalPrice items = foldrList (\item acc -> p item + acc) 0 items

或者简单地说:

totalPrice = foldrList (\item acc -> p item + acc) 0

暂无
暂无

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

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