我正在尝试使用内联和运算符......而不是特定的应用程序。
基于阅读诸如 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)
但是第一个工作示例和第二个示例之间有什么区别?
最佳答案
两个附加函数之间的主要区别在于第二个函数知道要解析的类型,它将是 TypeOf
'某事',它只是不知道'某事',但是 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
但是解析输出参数有什么意义呢?
在这种情况下没有任何意义,但对于类型函数来说是没有意义的。
关于f# - 内联和运算符重载问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39348813/