内联和运算符重载问题

时间:2016-09-06 12:14:15

标签: f#

我正在尝试使用内联和运算符....而不是特定的应用程序。

基于阅读的东西 http://nut-cracker.azurewebsites.net/blog/2011/11/15/typeclasses-for-fsharp/ 但不理解它。

如此。

我可以制作

type HelperType = HelperType with   
   static member (=>) (d:HelperType,x: list<char>) = fun y -> x @ y    
   static member (=>) (d:HelperType,x:array<char>) = fun y -> Array.append x y
   static member (=>) (d:HelperType,x:string     ) = fun y -> x + y

let inline append x = HelperType => x

let x1 = append "" ""
let x1 = append [|'a'|] [|'b'|]

工作......并且了解最新情况。

但是让我们尝试只重载类型而不是值......所以我去......

type TypeOf<'t> = | TypeOf

type HelperType = HelperType with   
   static member (<*>) (d:HelperType,x:TypeOf<list<char>>     )   = fun x y -> x @ y
   static member (<*>) (d:HelperType,x:TypeOf<array<char>>     )   = fun x y -> Array.append x y

即。我实际上并不需要类型的值只是一些代理类型值

我去了

let inline append2 (x : ^t) = (HelperType <*> (TypeOf :> TypeOf< ^t>)) x

我得到......

Error       A unique overload for method 'op_LessMultiplyGreater' could not be determined based on type information prior to this program point. A type annotation may be needed. Candidates: static member HelperType.( <*> ) : d:HelperType * x:TypeOf<char array> -> ('a0 [] -> 'a0 [] -> 'a0 []), static member HelperType.( <*> ) : d:HelperType * x:TypeOf<char list> -> ('a0 list -> 'a0 list -> 'a0 list)

但是第一个工作示例和第二个工作示例之间的区别是什么?

1 个答案:

答案 0 :(得分:3)

两个追加函数之间的主要区别在于第二个函数知道要解决的类型,它是 TypeOf 的&#39;某些&#39;,它只是不知道&#39; ;&#39;,但第一个例子中的append不知道它将解析哪种类型,因此它将重载决议推迟到调用站点。

因此,第二个示例尝试执行重载解析并失败。

<强>更新

您可能会对以下内容感兴趣:

type HelperType = HelperType with   
   static member (<*>) (d:HelperType, _:list<char> ) = fun (x:list<char>) y -> x @ y
   static member (<*>) (d:HelperType, _:array<char>) = fun (x:array<char>) y -> Array.append x y

let inline append2 x y :'T = (HelperType <*> Unchecked.defaultof<'T>) x y

但它需要提前知道返回类型:

let x1 : array<char> = append2 [|'a'|] [|'b'|]

或者你可以按照你已经想出的那样改变它:

let inline append2 (x:'T) y :'T = (HelperType <*> Unchecked.defaultof<'T>) x y

但那么解决输出参数的重点是什么?

在这种情况下没有任何意义,但对于类型函数,它会。