简体   繁体   中英

Calculate Price of items in a list

I am learning algebraic-data-types in Haskell, and I ran into a problem I cannot solve.

So I want to enter a list of groceries, and as an output I should get the total price.

For now, I have the types:

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

and I have the groceries list: list1 = A `Add` (B `Add` Empty)

I have a function (That sets the prices of the items):

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

And now here is where I have a difficulty. I want to apply the function "p" to my list1. But I am not sure how.

Here is my current code:

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

I also tried this.

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

Thanks in advance!

price 's first parameter is a function which accepts List parameter and returns Int (like the declared p function, but do not confuse it with p parameter in price p (Add x xs) pattern, I renamed the former one for clarity to c ), so the implementation can look like the following:

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

With call looking like price p $ Add A Empty (calculates price of list of one A).

In addition to chepner's suggestion to implement mapList I might suggest writing foldrList .

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

Having done so, the total price of a list of items can be calculated:

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

Or simply:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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