代码之家  ›  专栏  ›  技术社区  ›  MrD at KookerellaLtd

在函数上定义重载运算符

f#
  •  2
  • MrD at KookerellaLtd  · 技术社区  · 7 年前

    我想定义“关系”,但定义为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 回复  |  直到 7 年前