无法让绑定运算符与受歧视的联合一起工作

Can't get bind operator to work with discriminated union

我正在尝试在我的代码中使用 "bind operator" (>>=)。

如果我使用运算符,我会得到一个编译错误,如果我改为 "inline" 运算符应该做什么,它就可以工作。

type TestDI =
    private
    | A of string list
    | B of int list
with
    static member (>>=) (x: string list, f: TestDI -> 'a) =
        f <| A x

let func (t: TestDI) =
    match t with
    | A _ -> "a"
    | B _ -> "b"


// Expecting a type supporting the operator '>>=' but given a function type.
// You may be missing an argument to a function.
["a"] >>= func


// works
func <| A ["a"]

显然我遗漏了什么,有人可以帮忙吗?

当您使用运算符时,F# 会按顺序查找它:

  • 作为 let 定义的运算符;
  • 作为两个参数类型之一的 static member 定义的运算符。在这里,您传递给运算符的参数是 string listTestDI -> string,因此它不会查看您在 TestDI.
  • 上定义的参数

所以这里的解决方案是 let-定义它:

type TestDI =
    private
    | A of string list
    | B of int list

let (>>=) (x: string list) (f: TestDI -> 'a) =
    f <| A x