Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does function containing Console.ReadLine() not complete?

Tags:

recursion

f#

seq

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've been experimenting and researching this, and cannot see what is probably a very simple problem.

like image 593
octopusgrabbus Avatar asked Sep 22 '16 21:09

octopusgrabbus


People also ask

What type of data does console ReadLine () always return?

Return Value: It returns the next line of characters of string type from the input stream, or null if no more lines are available.

When you use console ReadLine () input data will be read as?

While Read() and ReadLine() both are the Console Class methods. The only difference between the Read() and ReadLine() is that Console. Read is used to read only single character from the standard output device, while Console. ReadLine is used to read a line or string from the standard output device.

What is console in ReadLine?

The Console. ReadLine() method in C# is used to read the next line of characters from the standard input stream.

What is console ReadLine in VB net?

The ReadLine method reads a line from the standard input stream. (For the definition of a line, see the paragraph after the following list.) This means that: If the standard input device is the keyboard, the ReadLine method blocks until the user presses the Enter key.


1 Answers

Sequences in F# are not evaluated immediately, but rather only evaluated as they're enumerated.

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
like image 98
Reed Copsey Avatar answered Sep 28 '22 07:09

Reed Copsey