Sum of the first elem of a 3-tuples list

人盡茶涼 提交于 2020-01-04 09:41:11

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!