Khanzor
Khanzor

Reputation: 5000

Recursive object warning using a seq expression

I've got the following (simplified) code:

open System
open System.IO

[<EntryPoint>]
let main argv =     
    let rec lineseq = seq {
        match Console.ReadLine() with
        | null -> yield! Seq.empty
        | line ->
            yield! lineseq
        }

    0

Visual studio is emitting an "recursive object" warning for the second yield statement, namely yield! lineseq.

Why is this?

Upvotes: 3

Views: 125

Answers (1)

Gus
Gus

Reputation: 26174

This is because you are defining lineseq as a value.

Just write #nowarn "40" at the beginning as the warning suggest, or add a dummy parameter so it becomes a function:

open System
open System.IO

[<EntryPoint>]
let main argv =     
    let rec lineseq x = seq {
        match Console.ReadLine() with
        | null -> yield! Seq.empty
        | line ->
            yield! lineseq x
        }

    // But then you need to call the function with a dummy argument.
    lineseq () |> ignore

    0

Also note that the sequence will still not be evaluated, and ReadLine will return no null, I guess you are waiting for an empty line which is "".

Try something like this in order to visualize the results:

let main argv =     
    let rec lineseq x = seq {
        match Console.ReadLine() with
        | ""   -> yield! Seq.empty
        | line -> yield! lineseq x}

    lineseq () |> Seq.toList |> ignore
    0

It has a ressemblance to this question: Recursive function vs recursive variable in F#

Upvotes: 3

Related Questions