좋아, 그래서 나는 내 텍스트 파일에서 한 줄당 평균 숫자로 연도를 인쇄하는 방법을 알아 내려고 이틀 동안이 골칫거리에 접근했습니다. 며칠 전에 비슷한 질문을했는데 기본적으로 같은 질문을 했습니다. 줄당 총 요소의 평균 값과 함께 텍스트 파일에서 줄을 재귀 적으로 인쇄하려면 어떻게해야합니까?
계속됩니다. 그러나 몇 가지 기능을 만들었습니다. 자, 여기 내 새로운 질문이 있습니다. 내 프로그램의 출력이 아래 그림과 같은 이유는 무엇입니까? 내 코드에서 몇 가지 질문을 주석 처리했습니다. 나는 다음과 같은 출력을 기대하고 있었다.
2010: 3.5788888
2009: 4.697858
This list goes on recursively.
업데이트 된 코드는 다음과 같습니다.
let ReadFile filename =
[ for line in System.IO.File.ReadLines(filename) -> line ]
let ParseLine (line:string) =
let strings = line.Split('\t')
let strlist = Array.toList(strings)
let year = System.Int32.Parse(strlist.Head)
let values = List.map System.Double.Parse strlist.Tail
(year, values)
let rec print (year, values) =
if values = [] then
()
else
printfn "%A: %A" year values.Head
print (year, values.Tail)
let avg (values:double list) = //this function can compute the average, but it wont work when I do in main, print(firstYear, avg (firstYear1))
let rec sum values accum =
match values with
| [] -> accum
| head :: tail -> sum tail (accum + head/12.0)
sum values 0.0
let rec sum (year, values:double list) =
if values = [] then
0.0
else
values.Head + sum (year, values.Tail)
[<EntryPoint>]
let main argv =
// read entire file as list of strings:
let file = ReadFile "rainfall-midway.txt"
printfn "** Rainfall Analysis Program **"
printfn ""
// let's parse first line into tuple (year, list of rainfall values),
// and then print for debugging:
let (year, values) = ParseLine file.Head
let firstYear = file.Head
let firstYear1 = file.Tail
//let data = List.map ParseLine file //I know map would be the key, but how does this work with year and its elements?
//let firstYear = data.Head
//let firstYear = data.Head
//print firstYear
print (firstYear, firstYear1)
//let S = sum firstYear
//printfn "%A" S
//let A = S / 12.0
//printfn "%A" A
// done:
printfn ""
printfn ""
0 // return 0 => success
가지고있는 코드는 실제로 예상 한 데이터를 제공하는 데 매우 가깝습니다. 작업을 단순화하기 위해 몇 가지 변경할 수 있습니다.
먼저 질문에 답하십시오
내 프로그램의 출력이 아래 그림과 같은 이유는 무엇입니까?
이것은 연도와 파싱 된 모든 값을 인쇄하기 때문입니다 (파일을 인쇄하는 코드와 일치하지 않음). 이를 해결하는 쉬운 방법은 ParseLine
함수가 평균을 계산하도록하는 것입니다. 함수 avg
이전 으로 이동 ParseLine
해야하지만 문제가되지 않습니다.
let avg (values:double list) =
let rec sum values accum =
match values with
| [] -> accum
| head :: tail -> sum tail (accum + head/12.0)
sum values 0.0
let ReadFile filename =
[ for line in System.IO.File.ReadLines(filename) -> line ]
let ParseLine (line:string) =
let strings = line.Split('\t')
let strlist = Array.toList(strings)
let year = System.Int32.Parse(strlist.Head)
let values = List.map System.Double.Parse strlist.Tail
(year, avg values) // calculate avg here
완료되면 맵을 사용하여 파일의 모든 행에서 ParseLine을 실행할 수 있습니다.
let result = file |> List.map ParseLine
그런 다음 결과를 인쇄하려면 결과 목록을 반복하기 만하면됩니다.
result |> List.iter(fun (year, avgRainfall) -> printfn "%i: %f" year avgRainfall)
즉, sum 및 avg 함수를 모두 제거하고 ParseLine
함수 에서 대신 fold를 사용할 수 있습니다.
let ParseLine (line:string) =
let strings = line.Split('\t')
let strlist = Array.toList(strings)
let year = System.Int32.Parse(strlist.Head)
year, (strlist.Tail |> List.fold(fun state el -> (System.Double.Parse el + state)) 0.0) / float strlist.Tail.Length
ParseLine
기능 을 변경하지 않으려면 다음을 수행 할 수 있습니다.
let result = file |> List.map(fun el ->
let (year, values) = ParseLine el
(year, avg values))
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다