【问题标题】:F# forcing a user to input an integerF# 强制用户输入整数
【发布时间】:2018-01-04 02:13:30
【问题描述】:

假设我要使用以下内容读取用户的输入:

let input = Console.ReadLine()

如何验证用户的输入,使其必须是整数,否则会显示错误消息?

【问题讨论】:

  • 您可以使用Int32.TryParse 对输入进行模式匹配。

标签: validation input f#


【解决方案1】:

稍微扩展@s952163的评论。

您可以像这样以典型的方式进行验证:

let parse (s: string) =
    match (System.Int32.TryParse(s)) with
    | (true, value) -> value
    | (false, _) -> failwith "Invalid int"

请注意,此函数具有 int 的返回类型以及异常的隐式返回类型。

解析整数的更惯用方法是纯函数:

let parse (s: string) =
    match (System.Int32.TryParse(s)) with
    | (true, value) ->  Ok value
    | (false, _) -> Error "Invalid int"

此函数的返回类型为 Result,这意味着所有输入都映射到显式输出。

然后,更大的程序可以由函数组成,这些函数只使用可以使用 Result 模块中的组合器(如 map 和 bind)解析输入的情况。

https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/results

【讨论】:

    【解决方案2】:

    我更喜欢使用活动模式来处理 F# 中的解析。您可以为要解析的每种类型创建一个 Active Pattern,例如:

    let (|Int32|_|) (str: string) =
        match Int32.TryParse(str) with
        | (true, value) -> Some value
        | _ -> None
    

    您可以为 Int64、Bool、DateTime 等创建类似的 Active Pattern。然后,您可以这样使用它们:

    match Console.ReadLine() with 
    | Int32 i -> printfn "Integer: %d" i 
    | invalid -> printfn "Error: %s is not an Integer" invalid
    

    【讨论】:

      猜你喜欢
      • 2013-08-07
      • 2011-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-23
      • 2013-02-26
      • 1970-01-01
      相关资源
      最近更新 更多