Why is the function containing Console.ReadLine () not completed?

I am using Visual Studio 2012, and the function that calls Console.ReadLine() will not execute

let inSeq = readlines ()

in this simple program

 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 experimented and researched this, and I don’t see what could be a very simple problem.

+5
source share
2 answers

Sequences in F # are not evaluated immediately, but rather evaluated as they are listed.

This means that your readlines function does nothing efficiently until you try to use it. By doing something with inSeq , you will force an assessment, which in turn will make it behave just as you expect.

To see this in action, do something that will enumerate the sequence, for example, 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 
+7
source

If you change the sequence to a list in readLines (), you do not need to “activate” the sequence to run the input recursion:

 open System open System.Collections.Generic open System.Text open System.IO #nowarn "40" let rec readlines () = [let line = Console.ReadLine() if not (line.Equals("")) then yield line yield! readlines ()] [<EntryPoint>] let main argv = let inList = readlines () printfn "END" Console.ReadLine() |> ignore 0 

A non-recursive approach might be something like this:

 let readLines _ = List.unfold (fun i -> let line = Console.ReadLine() match line with | "" -> None | _ -> Some (line, i)) 0 
0
source

All Articles