Reputation: 923
I've got a list of tuples inside another list and I am having problems finding the average.
I've checked over the asked questions and around the internet but most of the time they don't cover adding all of the tuples together and diving.
My list tuple list is [(String, Int)]
and I want to be able to find the average of all of the tuples.
Upvotes: 1
Views: 8173
Reputation: 704
Also, given a list of the form [(String,Int)]
you may use the unzip function, which has type
[(a,b)] -> ([a],[b])
So to get the average of a list that looks like [(String,Int)], you would simply use:
(sum $ snd $ unzip myList) / length(myList)
You'll need to correct the type so that you can divide using the fromIntegral function.
So, you might write the following function:
average :: [(a,Int)] -> Double
average xs = (fromIntegral $ sum $ snd $ unzip xs) / (fromIntegral $ length xs)
Upvotes: 1
Reputation:
Here's a way to calculate the sum and length in a single pass.
It's not pretty, but it works.
averageTuples ts = let results = calculateSum ts
in (fst results)/(snd results)
calculateSum ts = foldr acc (0,0) $ zip (map snd ts) (repeat 1) where
acc (x, y) (x', y') = (x+x', y+y')
main = print $ averageTuples [("foo", 1.09), ("bar", 2.6789), ("baz", 3.4)]
Keep in mind that you might have to use fromIntegral
if you have a list of all Ints
Upvotes: 0
Reputation: 237010
You can easily transform that to a list of simple integers with map snd
. So basically, sum $ map snd listOfTuples
to add them all together. (To efficiently calculate an average, you might want to do something a little more sophisticated, but this should put you on the right track.)
Upvotes: 4