问题
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?
回答1:
Use sum
with a list comprehension:
sum [x | (x, _, _) <- tuples]
回答2:
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
来源:https://stackoverflow.com/questions/8373631/sum-of-the-first-elem-of-a-3-tuples-list