f# - 使用标准输入初始化函数

标签 f#

我面临着一个让我迷失方向的问题,因为这应该是一个非常基本的过程。我正在学习如何使用 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

如何将值传递给 printfnsquare,就像我在 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/

相关文章:

testing - F# 是否具有访问词法作用域的语言构造(如 python locals()/globals())

Task.ContinueWith 的 F# 异步等价物

f# - 参数定义在哪里

f# - Elmish.WPF 中子模型到父模型/主模型的消息传递是如何完成的?

f# - 寓言 F# 到 Javascript : Parameterless functions being given a parameter when referenced

c# - 使用 C# 可移植库中的 F# 可移植类库

.net - F# 事件和处理程序的类型参数是什么?

arrays - 如何分配 RAM 容纳不下的单个数组

f# - 为什么 F# printfn 没有根据 Console.WriteLine 实现?

f# - F#中两种偏应用方式的区别