使用seq表达式的递归对象警告

时间:2014-03-21 06:29:48

标签: f#

我有以下(简化)代码:

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正在为第二个yield语句发出“递归对象”警告,即yield! lineseq

为什么会这样?

1 个答案:

答案 0 :(得分:3)

这是因为您将lineseq定义为值。

只需在警告提示时在开头写 #nowarn "40" ,或添加一个虚拟参数,使其成为一个函数:

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

另请注意,序列仍未被评估,ReadLine将不返回null,我猜您正在等待""的空行。

尝试使用这样的方法来显示结果:

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

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

它对这个问题有所了解:Recursive function vs recursive variable in F#