F# 模式匹配问题?
我在与 F# 进行模式匹配时遇到问题。我正在构建一个 F# 库,到目前为止已经有了:
namespace parser
module parse =
let public y = function
| x when x.Contains("hi") -> "HELLO"
| x when x.Contains("hello") -> "HI"
| x -> x
但它给了我错误:根据此程序点之前的信息对不确定类型的对象进行错误查找。在此程序点之前可能需要类型注释来约束对象的类型。这可以使查找得以解决。
I have a problem when pattern matching with F#. I'm building an F# library and have this so far:
namespace parser
module parse =
let public y = function
| x when x.Contains("hi") -> "HELLO"
| x when x.Contains("hello") -> "HI"
| x -> x
but it gives me error: Error Lookup on object of indeterminate type based on information prior to this program point. A type annotation may be needed prior to this program point to constrain the type of the object. This may allow the lookup to be resolved.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
本质上,编译器不理解您希望函数的参数为
string
类型。基本上,您不能对隐式声明的函数参数调用实例方法。您需要使用类似以下内容的内容。有趣的是,如果您没有调用实例方法,而是以其他方式使用它(类型已知),那就没问题。换句话说,假设
StringUtils
模块包含一个Has
方法,该方法接收两个字符串并执行与Contains
相同的检查;如果是这样,您可以使用隐式参数,因为编译器已经知道该值必须是哪种类型。显然,在很多情况下,这种事情是不必要的冗长。但它展示了 F# 类型推断行为的更重要的一点。
Essentially, the compiler doesn't understand that you want the argument to your function to be of type
string
. Basically, you can NOT invoke instance methods on implicitly declared function arguments. You'll need to use something like the following.Interestingly, if you were not invoking an instance method, but instead using it in some other way (where the type was already known), you would be fine. In other words, suppose a
StringUtils
module contained a methodHas
, which took in two strings and performed the same check asContains
; if so, you could use the implicit argument, because the compiler already knows of which type the value must be.Obviously, in many cases, this sort of thing is unnecessarily verbose. But it demonstrates the larger point about F#'s type inference behavior.
编译器想要知道
y
函数中x
的类型,因此您需要对其进行注释,如下所示:The compiler wants to know the type of
x
is in youry
function so you need to annotate it, like this: