我是F#的新手,我正在編寫一些小挑戰來學習有關該語言的基本細節。由於不可變性,我認爲我有一個問題。F#不變性,純功能和副作用
場景: 我必須在控制檯中讀取高度線,每行包含一個整數。該整數代表山的大小。 閱讀輸入後,我需要寫出最高山脈的行數。 如果給出的指數是最高的山,那麼大小設置爲零,否則我鬆動。 重複該場景,直到所有的山都將其大小設置爲零。
下面的代碼我寫道:
open System
type Mountain = {Id:int; Height:int}
let readlineInt() = int(Console.In.ReadLine())
let readMountainData id = {Id = id; Height = readlineInt()}
let readAllMountainsData = [ for a in 0 .. 7 do yield readMountainData a ]
let rec mainLoop() =
let mountains = readAllMountainsData
let highestMountain = mountains |> List.maxBy (fun x -> x.Height)
printfn "%i" highestMountain.Id
mainLoop()
mainLoop()
該代碼將無限循環,我相信這是因爲
let readlineInt() = int(Console.In.ReadLine())
是不變的,所以該值設置一次,它的後永遠不要再停下來閱讀這一行。我試圖把'可變'關鍵字
let mutable readAllMountainsData = [ for a in 0 .. 7 do yield readMountainData a ]
但它沒有改變一件事。 你有什麼想法嗎?
編輯: 我知道這個代碼進入無限循環,因爲後面添加登錄到主循環如下:
let rec mainLoop() =
let mountains = readAllMountainsData
Console.Error.WriteLine("Mountain Count:{0} ", mountains.Length)
mountains |> List.iter (fun x -> Console.Error.WriteLine("Mountain Id:{0} Height:{1}", x.Id, x.Height))
let highestMountain = mountains |> List.maxBy (fun x -> x.Height)
printfn "%i" highestMountain.Id
mainLoop()
然後,我有這樣的輸出:
Standard Error Stream:
Mountain Count:8
Mountain Id:0 Height:9
Mountain Id:1 Height:8
Mountain Id:2 Height:7
Mountain Id:3 Height:6
Mountain Id:4 Height:5
Mountain Id:5 Height:4
Mountain Id:6 Height:3
Mountain Id:7 Height:2
Mountain Count:8
Mountain Id:0 Height:9
Mountain Id:1 Height:8
Mountain Id:2 Height:7
Mountain Id:3 Height:6
Mountain Id:4 Height:5
Mountain Id:5 Height:4
Mountain Id:6 Height:3
Mountain Id:7 Height:2
Mountain Count:8
Mountain Id:0 Height:9
Mountain Id:1 Height:8
Mountain Id:2 Height:7
etc...
爲什麼我要重讀該值?因爲這些值是由外部來源提供的。所以工作流程如下:
Loop one:
I read 8 values for the height of the mountains in the console
I output the value of the highest mountain
Loop two:
I read 8 values for the height of the mountains in the console
I output the value of the highest mountain
Loop three:
I read 8 values for the height of the mountains in the console
I output the value of the highest mountain
etc
你爲什麼認爲代碼進入無限循環? –
我剛剛編輯帖子回答你的問題。這是因爲如果我在錯誤流中打印數據,我可以看到它。 –