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 acceptsListparameter and returnsInt(like the declaredpfunction, but do not confuse it withpparameter inprice p (Add x xs)pattern, I renamed the former one for clarity toc), so the implementation can look like the following:With call looking like
price p $ Add A Empty(calculates price of list of one A).