Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of the first elem of a 3-tuples list

Tags:

haskell

tuples

I'm new around programming stuff :/

I need to make a function that retrieve the sum of the first element from a 3-tuple list.

I have something like:

tuples = [(11,"11","11"),(22,"22","22"),(33,"33","33"),(44,"44","44"),(55,"55","55"),(66,"66","66")]

And I need the sum of the first element of each 3-tuple from the list. = 11+22+33+44+55

Pattern matching maybe? map?

like image 388
Nomics Avatar asked Jan 29 '26 07:01

Nomics


2 Answers

Use sum with a list comprehension:

sum [x | (x, _, _) <- tuples]
like image 199
hammar Avatar answered Jan 30 '26 19:01

hammar


If you want something pointfree, you could try:

> let f = sum . map (\(x, _, _) -> x)
> f [(11,"11","11"),(22,"22","22"),(33,"33","33")]
66

Note: this has point x, which we can not avoid because of the fst3 :: (a,b,c) -> a built-in lack

like image 41
Matvey Aksenov Avatar answered Jan 30 '26 19:01

Matvey Aksenov