扩展方法和约束函数

时间:2016-10-07 12:30:11

标签: f#

我想用连接方法和一个约束函数扩展选项类型。

type Option<'a> with 
    member this.join r =
        match r with
            | Some s -> 
                match s with
                    | Some really as r -> r
                    | _ -> None
            | _ -> None

调用方法可以正常工作。

let x = None.join(Some (Some 1))

现在我想定义一个重载函数(内联和约束,因为这是F#中的唯一方法)

let inline join (t:^T) : ^U = (^T : (member join : ^T -> ^U) (t,t))

并像这样称呼它

join (Some (Some 1))    

但现在我收到错误消息

The type ''a option' does not support the operator 'join'
union case Option.Some: Value: 'T -> Option<'T>
The representation of "Value of type 'T"

这是奇怪的,因为我可以写这样的另一种类型

type Result<'TSuccess, 'TError> = 
    | Success of 'TSuccess 
    | Error of 'TError list
    member this.join r =
        match r with
            | Success(s) -> 
                match s with
                    | Success(really) -> Success(really)
                    | Error(e) -> Error(e)
            | Error(e) -> Error e

并像这样使用

join (Success (Success 1))

不同之处在于,在这种情况下,没有扩展方法

任何想法?

0 个答案:

没有答案