F#模式匹配问题?

Mat*_*Sot 0 f# type-inference pattern-matching

与F#进行模式匹配时遇到问题.我正在构建一个F#库,到目前为止这个:

namespace parser
    module parse =
        let public y = function 
        | x when x.Contains("hi") -> "HELLO" 
        | x when x.Contains("hello") -> "HI" 
        | x -> x
Run Code Online (Sandbox Code Playgroud)

但它给了我错误:根据此程序点之前的信息查找不确定类型的对象的错误.在此程序点之前可能需要类型注释来约束对象的类型.这可以允许解析查找.

pbl*_*cci 7

本质上,编译器不理解您希望函数的参数是类型string.基本上,您不能在隐式声明的函数参数上调用实例方法.您需要使用以下内容.

let y (value:string) = 
  match value when
  | x when x.Contains("hi") -> "HELLO" 
  | x when x.Contains("hello") -> "HI" 
  | x -> x
Run Code Online (Sandbox Code Playgroud)

有趣的是,如果你没有调用实例方法,而是以其他方式使用它(类型已经知道),你会没事的.换句话说,假设一个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
Run Code Online (Sandbox Code Playgroud)

显然,在许多情况下,这种事情是不必要的冗长.但它证明了F#类型推理行为的重点.