4

I have a little problem with my code that i wrote it's for reading input from console in F# as sequence of lines. My problem is that it read only 5 lines of text and then end but it should read more lines. Would be nice if someone told me what is wrong whit this code.

screen from console

let allList = new List<string>()
let rec readlines () = seq {
  let line = Console.ReadLine()
  let b = allList.Add(line)
  if line <> null then
      yield line
      yield! readlines ()
}
let  b = readlines()
printf "%A" b
Rafal
  • 81
  • 9

1 Answers1

6

You're only getting the first 5 lines, because the result of readlines is a lazy sequence that is not fully evaluated - printing the sequence only prints first 5 elements and so that's all that gets evaluated.

You can easily see that this is how things work by running the following example:

let test = 
  seq { for i in 0 .. 1000 do 
          printfn "Returning %d" i
          yield i }

printfn "%A" test

An easy fix is to fully evaluate the lazy sequence by converting in to an in-memory list:

let  b = readlines() |> List.ofSeq
printf "%A" b

Alternatively, you could also iterate over the lines using for loop and print them one by one:

for line in readlines() do
  printf "%s" line
Tomas Petricek
  • 240,744
  • 19
  • 378
  • 553
  • 1
    It might be worth mentioning the some reasons why printing a sequence only prints the first five elements. – phoog Jan 10 '19 at 19:30