JamieB
JamieB

Reputation: 923

Haskell - Add tuples within a list together?

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

Answers (4)

rotskoff
rotskoff

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

user903589
user903589

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

Chuck
Chuck

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

dave4420
dave4420

Reputation: 47042

If you search the net, you find many average :: (Real a, Fractional b) => [a] -> b functions, e.g. here.

So you just need a function of type [(String, Int)] -> [Int], then you can put the two together.

Upvotes: 0

Related Questions