【问题标题】:Binding function result in "when" expression - F#绑定函数导致“when”表达式 - F#
【发布时间】:2019-11-19 13:07:33
【问题描述】:

我正在编写一个匹配项,我在函数 f 上使用“when”表达式限制匹配项。我想绑定 f 的结果以用于以下表达式。我希望我的代码看起来像这样:

match input with
| input when f x input -> //Some exp where (f x input) is used but not recomputed
| input when f y input -> //Some exp where (f x input) is used but not recomputed

显而易见的解决方案是简单地重新计算结果,但我想知道是否可以使用其他机制。

【问题讨论】:

  • 你不需要重新计算结果:如果模式匹配,你知道f x input = true
  • 在这个例子中,f 必须是一个布尔值,when f x input 才能正确编译。如果你想让f 成为一个返回任意类型的函数,你需要active patterns。特别注意IntBool 示例:如果活动模式的结果是Some x,则将其匹配为Int y 会将值x 分配给y。如果这还没有意义,请阅读文章并进行一些实验。
  • 或者只使用if 表达式。仅仅因为你有一把花哨的锤子并不意味着一切都必须是钉子。

标签: f# pattern-matching


【解决方案1】:

以下表达式中 f 的结果为“真”。如果你愿意,你可以使用 true 。如果您希望以某种方式匹配和转换匹配,则可以使用活动模式。

open System.Text.RegularExpressions
let (|FirstRegexGroup|_|) pattern input =
   let m = Regex.Match(input,pattern) 
   if (m.Success) then Some m.Groups.[1].Value else None  

let testRegex str = 
    match str with
    | FirstRegexGroup "http://(.*?)/(.*)" host -> 
           printfn "The value is a url and the host is %s" host
    | FirstRegexGroup ".*?@(.*)" host -> 
           printfn "The value is an email and the host is %s" host
    | _ -> printfn "The value '%s' is something else" str

// test
testRegex "http://google.com/test"
testRegex "alice@hotmail.com"

来源https://fsharpforfunandprofit.com/posts/convenience-active-patterns/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-29
    • 2014-05-24
    • 1970-01-01
    • 2017-06-30
    • 2020-08-15
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    相关资源
    最近更新 更多