如何从文本文件中递归打印行以及每行总元素的平均值? [英] How do I print out lines recursively from a text file along with the average value of total elements from per line?

查看:77
本文介绍了如何从文本文件中递归打印行以及每行总元素的平均值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题听起来有点挑战,但是在这里我发现没有任何与F Sharp相关的问题.好的,因为在上一个问题中我提到我是F#的新手.多亏了其他程序员的帮助,才能解决上一个问题中的求和函数.因此,我有一个文本文件,其中包含20多个行,并且我想打印出包含年份以及每年及其元素总数的平均值的行.

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.

示例文本行

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

和第二个函数可以完美地完成元素的总和,但是我无法设法将其正确地除以12个元素.

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

主要

  let (year, values) = ParseLine file.Head
  printfn "%A: %A" print (year (sum values)) // year gets the error, according to visual studio

推荐答案

感谢John Palmer发表了快速解决方案.固定代码是

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

这篇关于如何从文本文件中递归打印行以及每行总元素的平均值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆