recursionf#console.readline

F# Reading input from console


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

Solution

  • 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