user3053434
user3053434

Reputation: 3

Haskell Syntax: Adding ints from tuples in a list

I've searched the site but couldn't find anything specific to this problem..

I have a list that contains triples of strings and integers like so:

mylist = [("Amy", 6), ("Scott, 3"), ("Bradley", 4)]

I want to write a function that will just add up all the integers from this list

I currently have the function:

addMarks :: [(String, Int)] -> Int
addMarks pairList = [ j+j | (i,j) <- pairList ]

j+j doesn't work, I'm not sure on the correct syntax to add just the 'j's and leave the i.

Upvotes: 0

Views: 91

Answers (1)

Zeta
Zeta

Reputation: 105886

You want to sum over the second value of a pair. There's a function for summing over the content of a list (sum), and there's a function for getting the second value of a pair (snd):

addMarks = sum . map snd

map f takes a list and returns a new list by applying f to every element. If you want to use list comprehension for this, you would end up with

addMarks pairList = sum [ j | (_,j) <- pairList ]

since list comprehension is just syntactic sugar for filter and map.

Upvotes: 3

Related Questions