问题
I know this question sounds a bit challenging, but hey I find nothing like this relates with F sharp here. Okay so, since in my previous question I mentioned I'm new to F#. Thanks to several of fellow programmers' helps here to solve my sum function in my previous question. So, I have a text file that contained more than 20 lines and I want to print out lines with year and average of total elements from each year and its elements.
Sample text lines
2009 1.3 3.51 6.76 5.80 4.48 5.47 2.06 4.3 0.54 7.69 1.27 2.9
2008 3.53 3.71 1.88 2.46 4.63 4.88 4.53 1.51 10.83 2.7 1.28 6.51
2007 2.88 2.19 3.55 3.95 2 3.1 4.18 8.76 1.91 2.01 1.67 3.54
2006 3.48 1.33 3.16 3.87 3.19 3.87 4.24 7.12 4.32 6.63 2.97 3.37
2005 5.32 2.41 1.76 1.63 1.78 1.07 2.07 1.44 2.68 1.14 2.15 1.38
2004 1.09 0.75 3.93 1.9 5.57 2.94 4.46 5.01 0.86 2.42 5.02 1.75
....
Now, I have a couple functions to show you. Unfortunately, my print function only prints out the first line.
let rec print year values =
if values = [] then
()
else
printfn ""
printfn "%A: %A" year values
and the 2nd function which does the sum of elements perfectly, but I cannot manage to get it to divide it by 12 elements properly.
let sum (values: double list) =
let rec sum values accum =
match values with
| [] -> accum
| head :: tail -> sum tail (accum + head) / 12.0 // would 12.0 work right?
sum values 0.0
in the main
let (year, values) = ParseLine file.Head
printfn "%A: %A" print (year (sum values)) // year gets the error, according to visual studio
回答1:
Thanks to John Palmer who posted a quick solution. the fixed code is
let sum (values: double list) =
let rec sum values accum =
match values with
| [] -> accum
| head :: tail -> sum tail (accum + head/12.0)
sum values 0.0
来源:https://stackoverflow.com/questions/28491617/how-do-i-print-out-lines-recursively-from-a-text-file-along-with-the-average-val