patternModerate
Reading input from console in F# (as a sequence of lines)
Viewed 0 times
fromreadingsequenceinputconsolelines
Problem
Consuming input line-by-line until the end is often useful. In C# I would write the following loop:
I wanted to do this using "idiomatic" F# (which to me includes avoiding
The last line shows the following warning
Warning FS0040: This and other recursive references to the object(s)
being defined will be checked for initialization-soundness at runtime
through the use of a delayed reference. This is because you are
defining one or more recursive objects, rather than recursive
functions. This warning may be suppressed by using '#nowarn "40"' or
'--nowarn:40'.
The warning would suggest I am actually not writing idiomatic F# (as warnings usually point out problematic code). Is there a better way to write the function that avoids the warnings?
while ((line = Console.ReadLine()) != null) {
// ...I wanted to do this using "idiomatic" F# (which to me includes avoiding
let mutable) and I came up with this:let rec readlines = seq {
let line = Console.ReadLine()
if line <> null then
yield line
yield! readlines
}The last line shows the following warning
Warning FS0040: This and other recursive references to the object(s)
being defined will be checked for initialization-soundness at runtime
through the use of a delayed reference. This is because you are
defining one or more recursive objects, rather than recursive
functions. This warning may be suppressed by using '#nowarn "40"' or
'--nowarn:40'.
The warning would suggest I am actually not writing idiomatic F# (as warnings usually point out problematic code). Is there a better way to write the function that avoids the warnings?
Solution
What you have there is a value, but you probably want it to be a function:
let rec readlines () = seq {
let line = Console.ReadLine()
if line <> null then
yield line
yield! readlines ()
}Code Snippets
let rec readlines () = seq {
let line = Console.ReadLine()
if line <> null then
yield line
yield! readlines ()
}Context
StackExchange Code Review Q#96473, answer score: 11
Revisions (0)
No revisions yet.