Average of list of doubles

Viewed 140

I am having some issues writing a Haskell function. I am trying to get the average of a list of triples of doubles. when I divide by just the ' length xs ' , I get an error that the length is an Int, so I tried using fromIntegeral and its not giving me an error but not giving the right answer. For example if I test, averages [(2.0,1.0,3.0)] it returns [6.0]

averages :: [(Double, Double, Double)] -> [Double]
averages xs = [ (x+y+z) / fromIntegral (length xs) | (x,y,z) <- xs ]

3 Answers

You are missunderstanding your own type function, the avarage is always over 3, because you have a list of triplets (or tuples of three?):

averages :: [(Double, Double, Double)] -> [Double]
averages xs = [ (x+y+z) / 3 | (x,y,z) <- xs ]


$> averages [(8,6,7), (4,4,10), (1,1,1)]
=> [7.0,6.0,1.0]

Note that length xs will evaluate to 1 when you evaluate averages [(2.0,1.0,3.0)]. The list contains a single element: a tuple. Since you are averaging the elements of a triplet, you can just divide by 3.

Others have explained why you're getting the wrong answers, but I would like to urge you to break up your problem into two pieces.

averageTriple :: (Double, Double, Double) -> Double
averageTriple (x,y,z) = ...

averageTriples :: [(Double, Double, Double)] -> [Double]
averageTriples ts = ... -- use averageTriple here
Related