我面临着一个让我迷失方向的问题,因为这应该是一个非常基本的过程。我正在学习如何使用 F# 构建简单的控制台应用程序,但我不知道如何将整数作为标准输入传递给程序。请考虑:
open System
let square x = x * x
[<EntryPoint>]
let main (argv :string[]) =
printfn "The function will take an input and square it"
printfn "%d squared is %d" 12 (square 12)
Console.ReadLine() |> ignore
0
如何将值传递给 printfn
和 square
,就像我在 C 中所做的那样:
int main(){
int i;
scanf("%d", &i);
printf("\nThe value of variable i is %d.\n", i);
return 0;
}
我尝试调整 let x = Console.ReadLine()
来获取整数,但没有明显的结果。 documentation我咨询了,主要考虑字符串输入。我担心我错过了一些对于正确理解 F# 基础知识来说很重要的东西。从这个意义上讲,任何建议都将受到高度赞赏。
最佳答案
ReadLine()
将返回一个字符串。正如@JohnPalmer 提到的,它需要解析为 int。下面的程序应该可以让您了解基本的想法:
let rec input () =
printf "Input: "
match Core.int.TryParse (stdin.ReadLine ()) with
| true, i -> i
| _ ->
printfn "Invalid input, try again"
input ()
let square x = x * x
[<EntryPoint>]
let main _ =
printfn "The function will take an input and square it"
let i = input ()
printfn "%d squared is %d" i (square i)
0
关于f# - 使用标准输入初始化函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47220537/