Home > database >  Calculate Price of items in a list
Calculate Price of items in a list

Time:12-15

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!

CodePudding user response:

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).

  • Related