[英]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.