F#-打印匹配表达式结果

时间:2018-10-04 14:57:34

标签: f# match

我认为这很简单,但是过去一个小时我一直在尝试我能想到的一切,并在网上进行研究无济于事。 (我是F#的新手)

我有以下代码发送HTTP请求,然后将其与结果匹配。如果它不匹配任何内容(| _),我只想将其字符串值打印到控制台。我将如何去做?

    match Http.RequestString("http://foo.com/res.php", 
                          httpMethod = "GET", 
                          query = ["key", key; "action", "get"; "id", id]) with
     | "CAPCHA_NOT_READY" -> printfn "Sleeping for 5"
                             Thread.Sleep(5000)
                             GetCaptchaRequest id
     | _  -> printfn ???

1 个答案:

答案 0 :(得分:4)

当您不关心该值并且在后续代码中不再使用该值时,将使用下划线字符。您只需要给变量起一个名字即可。试试这个:

| msg -> printfn "%s" msg

在此示例中,我选择了msg作为变量名,但是它可以是您选择的任何有效变量名。

由于match语句的所有分支都必须返回相同的类型,因此您不仅需要printfn语句。在这种情况下,外部调用可能会失败,使用Option<'a>类型表示成功或失败是常见的习惯用法。

不知道您的API端点的详细信息,请考虑以下伪代码:

let GetCaptchaRequest id : string option =
        match Http.RequestString("http://foo.com/res.php", 
                              httpMethod = "GET", 
                              query = ["key", key; "action", "get"; "id", id]) with
         | "CAPCHA_NOT_READY" -> printfn "Sleeping for 5"
                                 Thread.Sleep(5000)
                                 GetCaptchaRequest id
         | "ERROR" -> printfn "Something went wrong!"
                      None
         | result  -> printfn "Successful result!"
                      Some (parseMyCaptchaResult result)