Average of a List

Hi Sirs / Mam.
I am new to Haskell. I am testing out few things which I learnt.
I was trying to find an average of the following list. And I don’t know how to do it. Kindly help.

type StudentRate = ( String , Int )

If I use this [StudentRate] as a list , how to find the average of the INt value.

Is there an idea you have in mind, something you have tried?

1 Like

This is how you could do it in ghci:

  1. Define a list, for example: let studentRates = [("Angela", 3), ("Olaf", 4)]
  2. Use the map function to apply snd to each element. The function snd extracts the second element from each tuple: let rates = map snd studentRates
  3. Calculate the sum of the rates: let sumRates = sum rates
  4. Count the number of elements in the rates list: let countRates = length rates
  5. Divide sumRates by countRates. But before you do that, convert countRates to a floating point number. Otherwise Haskell will complain: sumRates / (fromIntegral countRates)

This solution is admittedly not very elegant, but it allows to see the effect of each individual step.

1 Like

You may also improve the algorithm later to calculate average iteratively (on rationals) to avoid integer overflow and loss of precision.

1 Like

Hi All ,
I was researching and did this it’s as working.
realToFrac ( Sum ( map and sr)) / genericlength sr

Hi All,
thank you very much for all of ur valuable answers.

RealToFrac ( Sum ( map snd sr)) / genericlength sr

Hi Sirs/ Mam,
How to use printf ‘%3.3f’ on the float value obtained above

Here’s a well-documented function for that: Text.Printf

1 Like