我在玩 F# 时发现了一个我无法理解的问题。假设我想从用户那里获取一系列整数输入并将其存储在一个数组中:
[<EntryPoint>]
let main =
let n = Console.ReadLine() |> int
let inputVals = Array.zeroCreate n
for i in 0 .. n - 1 do
inputVals.[i] <- (Console.ReadLine() |> int)
printf "%A\n" inputVals
0 //compiler error here. The type does not match the expected type
但这给出了错误
This expression was expected to have type string [] -> int but here has type int
经过一番尝试后,我怀疑错误来自 for 循环。但我不明白为什么它需要一个 string[] -> int。这似乎是一个非常简单的问题,但我可以弄清楚发生了什么。
最佳答案
这里的错误与循环本身无关。您正在使用 main
作为值,但它应该是一个从字符串数组到 int
的函数。
[<EntryPoint>]
let main args =
// Your stuff here
0
其中 args
将被推断为 string[]
。
如果你觉得冗长,你可以拼写出来:
[<EntryPoint>]
let main (args : string[]) =
// Your stuff here
0
其他一切正常
关于for-loop - F# for 循环错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25914636/