【问题标题】:Initialize function with standard input使用标准输入初始化函数
【发布时间】:2017-11-10 19:05:45
【问题描述】:

我正面临一个让我迷失方向的问题,因为它应该是一个非常基本的程序。我正在学习如何使用 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# 基础的重要内容。从这个意义上说,任何建议都将受到高度赞赏。

【问题讨论】:

  • int.Parse() 是你的朋友
  • 谢谢@JohnPalmer,我会做一些练习。

标签: f#


【解决方案1】:

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

【讨论】:

  • 非常感谢这个简单的例子。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-24
  • 2021-11-12
相关资源
最近更新 更多