0

I have a text file of rain measured over 3 years, where each number after the year corresponds to the month. For example, in

2002    1.17    0.78    7.11    5.17    5.84    4.29    1.12    4.06    1.9 2.07    1.47    1.53
2001    1.24    3.22    1.61    3.33    6.55    2.4 3.5 1.32    3.9 6.04    1.69    1.13
2000    1.277   1.4 1.17    5.74    6.48    4.81    4.07    3.19    6.2 1.95    2.65    1.7

In 2002, Average rainfall in Feb was 0.78.

I made a list of tuples called mylist, in the format (year,values,average,min,max) where years is int, values is a float list, average is an int that averages all of 'values', min is an int holding the smallest 'value' and max.

My question: How do I calculate the average of the n'th elements in the list, like the average of month January, Feb, March....

I have:

 let months = [ "Jan"; "Feb"; "Mar"; "Apr"; "May"; "Jun"; "Jul"; "Aug"; "Sep"; "Oct"; "Nov"; "Dec" ] //string list

and I'm thinking of something along the lines of:

mylist |> List.map (fun (_,values, _, _, _) -> average 0th index across all tuples, print Jan, then average 1st index across all tuples, print Feb, etc...)

or

mylist |> List.map (fun (_,values, _, _, _) -> printfn"%A %A" List.average 0thIndex,0thMonth....List.average 1stIndex, 1stMonth, etc...)

But I'm not familiar enough with the functional language to know all operations on lists and maps. Am more comfortable with Java and C

SSOPLIF
  • 311
  • 1
  • 4
  • 15

1 Answers1

1

I would map values to list of lists:

 let vs = mylist |> List.map (fun (_, values, _, _, _) -> values)

Then transpose it to get list of lists of values in months.

 let mvs = vs |> transpose

And then calculate averages using:

 let avgs = mvs |> List.map List.average

Use transpose from this answer.

Oh, and if you want to print them in a nice way:

 avgs |> List.iteri (fun i avg -> printfn "Month %s average: %d" months.[i] avg)
Community
  • 1
  • 1
rkrahl
  • 1,159
  • 12
  • 18
  • Wow, there is a lot of syntax and commands to learn. Thank you, works as expected! – SSOPLIF Feb 14 '15 at 19:55
  • Looking at the way you are writing your solutions you should change the way you think about the problem. Try to think about data as list of values (where values can be lists also) and imagine how to transform them in the way you want, probably it will be a sequence of transformations, each consuming an output of previous one. When you'll get that all is left is to find a functions that will make these transformations. – rkrahl Feb 14 '15 at 20:48