在discrimated union类型声明中使用活动模式

Mo *_* B. 5 f# discriminated-union active-pattern

是否可以在discrimated union类型声明中使用活动模式?

更准确地说,请考虑以下玩具示例:

type T = 
    | A of int
    | B

let (|Negative|_|) t = 
    match t with
    | A n when n < 0 -> Some ()
    | _ -> None

let T_ToString = function
    | Negative () -> "negative!"
    | _ -> "foo!"
Run Code Online (Sandbox Code Playgroud)

现在假设我想覆盖T中的ToString().在T的类型声明中,我不能引用T_ToString,因为T_ToString尚未在那时声明.我无法在ToString()之前移动活动模式和T_ToString,因为此时尚未声明T.但这也不起作用:

type T = 
    | A of int
    | B

    static member (|Negative|_|) t = 
        match t with
        | A n when n < 0 -> Some ()
        | _ -> None

    override this.ToString () = 
        match this with
        | Negative () -> "negative!"
        | _ -> "foo!"
Run Code Online (Sandbox Code Playgroud)

Mo *_* B. 2

好的,我想我找到了一个解决方案:首先声明类型,然后在其外部声明活动模式,最后使用 ToString() 的重写实现来增强类型。

type T = 
    | A of int
    | B

let (|Negative|_|) t = 
    match t with
    | A n when n < 0 -> Some ()
    | _ -> None

type T with
    override this.ToString() = 
        match this with
        | Negative () -> "negative!"
        | _ -> "foo!"
Run Code Online (Sandbox Code Playgroud)

但是,这不太好,因为我收到警告

warning FS0060: Override implementations in augmentations are now deprecated. Override implementations should be given as part of the initial declaration of a type.
Run Code Online (Sandbox Code Playgroud)