gpt4 book ai didi

recursion - 为什么包含 Console.ReadLine() 的函数不完整?

转载 作者:行者123 更新时间:2023-12-04 17:44:42 24 4
gpt4 key购买 nike

我正在使用 Visual Studio 2012,以及调用 Console.ReadLine() 的函数不会执行
let inSeq = readlines ()
在这个简单的程序中

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

我一直在对此进行试验和研究,但看不出可能是一个非常简单的问题。

最佳答案

F# 中的序列不会立即求值,而只会在枚举时求值。

这意味着您的 readlines在您尝试使用它之前,函数实际上什么都不做。通过使用 inSeq 做一些事情,您将强制进行评估,这反过来会使其表现得更像您期望的那样。

要查看此操作,请执行一些枚举序列的操作,例如计算元素的数量:

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

关于recursion - 为什么包含 Console.ReadLine() 的函数不完整?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39649493/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com