与F#进行模式匹配时遇到问题。我正在构建一个F#库并且到目前为止这样做了:
namespace parser
module parse =
let public y = function
| x when x.Contains("hi") -> "HELLO"
| x when x.Contains("hello") -> "HI"
| x -> x
但是它给了我错误:基于此程序点之前的信息在不确定类型的对象上查找错误。在此程序点之前可能需要类型注释来约束对象的类型。这可能允许解析查找。
答案 0 :(得分:7)
基本上,编译器不理解您希望函数的参数是string
类型。基本上,您不能在隐式声明的函数参数上调用实例方法。您需要使用以下内容。
let y (value:string) =
match value when
| x when x.Contains("hi") -> "HELLO"
| x when x.Contains("hello") -> "HI"
| x -> x
有趣的是,如果你没有调用实例方法,而是以其他方式使用它(类型已经知道),你会没事的。换句话说,假设StringUtils
模块包含方法Has
,该方法接受两个字符串并执行与Contains
相同的检查;如果是这样,你可以使用隐式参数,因为编译器已经知道该值必须是哪种类型。
module StringUtils =
let has (word:string) value = word.Contains(value)
module Parse =
let y = function
| x when x |> StringUtils.has "hi" -> "HELLO"
| x when x |> StringUtils.has "hello" -> "HI"
| x -> x
显然,在很多情况下,这种事情是不必要的冗长。但它证明了关于F#类型推理行为的更大观点。
答案 1 :(得分:0)
编译器想要知道x
函数中y
的类型,因此您需要对其进行注释,如下所示:
let y (x: string) =
match x with
| x when x.Contains "hi" -> "HELLO"
| x when x.Contains "hello" -> "HI"
| x -> x