Home > Blockchain >  Haskell how to add together every second element of tuples in a list of tuples
Haskell how to add together every second element of tuples in a list of tuples

Time:10-25

I would like to make a function that adds together the second element of every tuple in a list. So far I have:

pizza :: [(String, Int)] -> Int
pizza [] = 0
pizza (((a),b):xs) = b   pizza xs

This works great but I come into a problem when i want to add another int after the recursion is done.

So what I get is:

> pizza[("Cheese",10),("Dough",5)]
15

I want to add another five after the recursion is done so I would get:

> pizza[("Cheese",10),("Dough",5)] 
20

How would I go about doing this?

CodePudding user response:

If an empty list of ingredients is supposed to yield 5 anyway, you can simply reflect this in your base case.

pizza :: [(String, Int)] -> Int
pizza [] = 5
pizza (((a),b):xs) = b   pizza xs

On the other hand, if this only occurs when the list passed in is not empty, you can create a helper function that adds the 5 as its base case for recursion, but the helper only gets used when the list passed in is non-empty.

pizza :: [(String, Int)] -> Int
pizza [] = 0
pizza lst = pizza' lst
  where
    pizza' [] = 5
    pizza' ((_, x):xs) = x   pizza' xs

Now calling pizza [] will yield 0, but pizza [("Cheese",10),("Dough",5)] will yield 20.

It is possibly to simplify pizza'. Willem Van Onsem's answer has some great directions on this.

CodePudding user response:

You can omit the recursion and work with a map instead:

pizza :: Num b => [(a, b)] -> b
pizza = (5  ) . sum . map snd

or more verbose:

pizza :: Num b => [(a, b)] -> b
pizza xs = 5   (sum (map snd xs))
  • Related