I have a Tuple representing a Product:
type Product = (String, Int, Float)
String is the name, Int the amount and Float the price or value.
Now i want to do the following: I got a List of Products and into that List i want to add a new Product. But if the Product is already in the List i just want to increase the amount. (For now i dont care what happens if the price/value is not the same)
"If already in List then increase amount of that Product. Else add it to the List"
Example Input: ("Beer", 9, 3) [("Beer", 1, 3),("Milk", 3, 3),("Tea", 10, 3)]
Expected Output: [("Beer", 10, 3),("Milk", 3, 3),("Tea", 10, 3)]
or
Example Input: ("Apple", 2, 1) [("Beer", 1, 3),("Milk", 3, 3),("Tea", 10, 3)]
Expected Output: [("Beer", 1, 3),("Milk", 3, 3),("Tea", 10, 3),("Apple", 2, 1)]
(The List has no order so it does not matter where the new Product is inside the List)
addProduct :: Product -> [Product] -> [Product]
Sounds easy enough and actually i got a working method that does this:
-- check if a name is inside a List
nameInList :: String -> [Product] -> Bool
nameInList n [(a,b,c)] = if (a == n) then True else False
nameInList n ((a,b,c):xs) = if (a == n) then True else nameInList n xs
-- add a product to a list if its not already in that list else just increase amount of that product
addProduct :: Product -> [Product] -> [Product]
addProduct (a,b,c) xs = if nameInList a xs then newList else (a,b,c) : newList
where newList = [ (a2,b2+b,c2) | (a2,b2,c2) <- xs, a2 == a ] ++ [ (a2,b2,c2) | (a2,b2,c2) <- xs, a2 /= a]
But i was wondering if i can somehow achieve the same using pattern matching and recursion. I also feel like it should be possible without another function that does some checking.