简体   繁体   English

F#重载泛型类型的运算符

[英]F# overloading operators for generic types

I'm trying to define a module containing a generic type with operator overloading, but the mono compiler seems to ignore my types in the implementation file. 我正在尝试定义一个包含带有运算符重载的泛型类型的模块,但是单声道编译器似乎忽略了实现文件中的类型。 My interface file looks like: 我的界面文件如下:

module Vector
[<Sealed>]
type Vector<'a> =
  static member ( +. ) : Vector<'a> * Vector<'a> -> Vector<'a>
val make : 'a * 'a -> Vector<'a>
val coord : Vector<'a> -> 'a * 'a

And my implementation is 我的实施是

module Vector
type Vector<'a> =
  | V of 'a * 'a
  static member ( +. ) (V(x1,y1), V(x2,y2)) = V(x1+x2, y1+y2)
let make (x, y) = V(x, y)
let coord (V(x, y)) = (x, y)

When I compile I get: 当我编译时,我得到:

fsharpc -a VectorParam.fsi VectorParam.fs
F# Compiler for F# 3.1 (Open Source Edition)
Freely distributed under the Apache 2.0 Open Source License

/.../VectorParam.fs(4,19): error FS0034: Module 'Vector' contains
    static member Vector.( +. ) : Vector<int> * Vector<int> -> Vector<int>    
but its signature specifies
    static member Vector.( +. ) : Vector<'a> * Vector<'a> -> Vector<'a>    
The types differ

which I don't understand, since I'm using a tagged type. 我不明白,因为我使用的是标记类型。 And, if I remove all "<'a>" and replace remaining type aliases with float, then everything works fine. 并且,如果我删除所有“<'a>”并用float替换剩余的类型别名,那么一切正常。 Can anyone help me understand the right syntax? 任何人都可以帮我理解正确的语法吗?

Thanks, Jon 谢谢,乔恩

I would start by ditching the fsi file - it is not really required. 我会从放弃fsi文件开始 - 这不是真的需要。 If you really need it, the easiest way to create it is by pasting your file into fsi and copying the output, or you can get the compiler to generate one for you. 如果你真的需要它,创建它的最简单方法是将文件粘贴到fsi并复制输出,或者你可以让编译器为你生成一个。

When doing type inference over numeric types it is best to use inline members. 在对数字类型进行类型推断时,最好使用内联成员。 The reason is that F# really likes to use int - and as soon as it sees a + with no further constraints the compiler will infer int . 原因是F#真的喜欢使用int - 只要它看到一个没有进一步约束的+ ,编译器就会推断int This is because in the .NET type system, not all of the constraints used by F# can be expressed. 这是因为在.NET类型系统中,并不能表达F#使用的所有约束。 Using inline bypasses this. 使用inline绕过这个。

Here is a simple example that can be pasted straight into fsi: 这是一个可以直接粘贴到fsi的简单示例:

type Vector<'a> =
  | V of 'a * 'a
  static member inline ( +. ) (V(x1,y1), V(x2,y2)) = V(x1+x2, y1+y2);;

V(1,1) +. V(1,1);;
V(1.,1.) +. V(1.,1.);;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM