在函数上定义重载运算符

时间:2018-09-25 16:13:26

标签: f#

我想定义“关系”,但定义为Identity <'a>,seq <'a>和Option <'a>的函数。

我从未在F#中定义重载运算符。

使用“ +”会很好!

   open FSharpPlus.Data

   type Relation = 
// ('a -> Identity<'b>) -> ('b -> 'c) -> ('a -> 'c)
    static member (+) (f,g) = 
        fun a ->  g ((f a) |> Identity.run)
// ('a -> #seq<'b>) ->  ('b -> #seq<'c>) -> ('a -> seq<'c>) 
    static member (+) (f , g ) = 
        fun a -> seq {
                    for b in f a do
                        yield! g b
                    }
// ('a -> seq<'b>) -> ('b -> Identity<'c>) -> ('a -> seq<'c>) 
    static member (+) (f,g) = 
        fun a -> seq {
                    for b in f a do
                        yield Identity.run (g b)
                    }

这会编译...

然后我尝试使用它;

member x.foo () = 
    let f1 : int -> Identity<int> = fun x -> Identity x
    let f2 : int -> seq<int> = fun x -> Seq.singleton x
    let x = f2 + f1
    ()

我得到:

FS0043  Expecting a type supporting the operator '+' but given a function type. You may be missing an argument to a function.
我做傻事吗? (是的!)

0 个答案:

没有答案