【问题标题】:F# Partial Active Pattern Matching "Rule Will Never Be Matched"F# 部分主动模式匹配“规则永远不会被匹配”
【发布时间】:2013-07-22 05:47:50
【问题描述】:

鉴于以下活动模式:

let (| HasMatch |) (x:string) = 
  if x.Contains("0") then Some()
  else None;;

还有下面的模式匹配函数:

let testFn x = function
  | HasMatch i -> printfn "%A" i
  | _ -> printf "nope";;

最后一行的通配符模式是warning FS0026: This rule will never be matched

我看到的所有示例似乎都推断出部分活动模式必须返回Some('a) 才能匹配,而返回None 的模式会被通配符捕获。错误似乎有不同的说法。

我错过了什么?

【问题讨论】:

  • 您描述了一个部分活动模式,但您试图用一个案例来定义它。这里有一些相当不错的教程:hestia.typepad.com/flatlander/2010/07/…底部的总结描述了文章中详细介绍的不同类型。

标签: f# pattern-matching active-pattern


【解决方案1】:

我认为你应该将None case 添加到活动模式声明中,如下所示:

let (| HasMatch | _ |) (x:string) = 
  if x.Contains("0") then Some()
  else None;;

在您的原始示例中,编译器推断您实际上想要返回 Option 类型。当您在示例中运行 printf 时,您会看到它在匹配时打印 Some Null

另外,返回Some() 是不好的,你应该返回Some(x) 或类似的内容

【讨论】:

  • 是的,def忘了| _ |
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-17
  • 2022-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多