问题描述
我正在使用Visual Studio 2012,并且调用 Console.ReadLine()
的函数将无法执行
I am using Visual Studio 2012, and the function that calls Console.ReadLine()
will not execute
让inSeq = readlines()
在这个简单的程序中
open System
open System.Collections.Generic
open System.Text
open System.IO
#nowarn "40"
let rec readlines () =
seq {
let line = Console.ReadLine()
if not (line.Equals("")) then
yield line
yield! readlines ()
}
[<EntryPoint>]
let main argv =
let inSeq = readlines ()
0
我一直在对此进行实验和研究,但看不到什么可能是一个非常简单的问题.
I've been experimenting and researching this, and cannot see what is probably a very simple problem.
推荐答案
F#中的序列不会立即求值,而只会在枚举时求值.
Sequences in F# are not evaluated immediately, but rather only evaluated as they're enumerated.
这意味着您的 readlines
函数实际上不会执行任何操作,直到您尝试使用它为止.通过使用 inSeq
进行操作,您将强制执行评估,这反过来会使它的行为更像您期望的那样.
This means that your readlines
function effectively does nothing until you attempt to use it. By doing something with inSeq
, you'll force an evaluation, which in turn will cause it to behave more like you expect.
要查看此操作的实际效果,请执行一些将枚举序列的操作,例如计算元素数量:
To see this in action, do something that will enumerate the sequence, such as counting the number of elements:
open System
open System.Collections.Generic
open System.Text
open System.IO
#nowarn "40"
let rec readlines () =
seq {
let line = Console.ReadLine()
if not (line.Equals("")) then
yield line
yield! readlines ()
}
[<EntryPoint>]
let main argv =
let inSeq = readlines ()
inSeq
|> Seq.length
|> printfn "%d lines read"
// This will keep it alive enough to read your output
Console.ReadKey() |> ignore
0
这篇关于为什么包含Console.ReadLine()的函数不完整?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!