如何为所有数字类型创建一个通用类?
我正在尝试创建一个对所有数字类型通用的 Vector 类。 我最初的尝试是为所有类型编写一个类,如下所示:
class Vector3f(val x:Float, val y:Float, val z:Float)
由于 scala 支持专门的注释,我可以使用它为所有数字类型生成这些类
class Vector3[A <: What?](val x:A,val y:A, val z:A)
,但我发现作为数字超级类型的所有内容都是 AnyVal,但 AnyVal 不是支持+-*/。那么,在不牺牲未装箱数字类型性能的情况下执行此操作的正确方法是什么?
I am trying to create a Vector class that is generic for all numeric types.
my original attempt was to write a class for all Types like this:
class Vector3f(val x:Float, val y:Float, val z:Float)
since scala supports the specialised annotation I could use this to generate me these classes for all numeric types
class Vector3[A <: What?](val x:A,val y:A, val z:A)
but everything I found as a super type for numbers was AnyVal, but AnyVal does not support + - * /. So what is the right way to do this, but without sacrificing the performance of unboxed number types?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你不能。现在不行。也许什么时候,如果,
Numeric
变得专业化。假设您获得了最简单的参数化类:
+
方法将编译成大致如下所示的内容:这就是 scalac -optimize -Xprint:jvm 输出。现在,甚至每个专用类型都有子类,因此您可以在不装箱的情况下初始化
Vector3
,但只要Numeric
不是专用的,您就无法更进一步。好吧...您可以编写自己的
Numeric
并对其进行专门化,但是,在这一点上,我不确定通过首先对类进行参数化您会获得什么。You can't. Not right now. Maybe when, and if,
Numeric
gets specialized.Say you get the simplest parameterized class possible:
The method
+
will compile into something roughly like this:That's
scalac -optimize -Xprint:jvm
output. Now there are even subclasses for each specialized type, so that you can initialize aVector3
without boxing, but as long asNumeric
is not specialized, you can't go further.Well... you can write your own
Numeric
and specialize that, but, at that point, I'm not sure what you are gaining by making the class parameterized in first place.简短的回答是:您无法获得全部性能。或者至少我还没有找到任何可以提供充分性能的东西。 (我已经在这个用例中尝试了一段时间;我放弃了并编写了一个代码生成器,特别是因为你也不能一般地处理不同的向量大小。)
我很高兴以其他方式显示,但到目前为止,我尝试过的所有操作都在运行时间上有小幅(30%)到大幅(900%)的增加。
编辑:这是一个显示我的意思的测试。
和输出:
The short answer is: you can't get full performance. Or at least I haven't found anything that gives full performance. (And I have tried for a while in exactly this use case; I gave up and wrote a code generator instead, especially since you can't handle different vector sizes generically either.)
I'd be delighted to be shown otherwise, but thus far everything I've tried has had a small (30%) to vast (900%) increase in runtime.
Edit: here's a test showing what I mean.
and the output:
您可能想使用此处描述的类型类模式: http ://dcsobral.blogspot.com/2010/06/implicit-tricks-type-class-pattern.html
或者,您可以通过使用数字特征 http://www.scala-lang.org/api/current/scala/math/Numeric.html
You probably want to use the typeclass pattern as described here: http://dcsobral.blogspot.com/2010/06/implicit-tricks-type-class-pattern.html
Or, you can indirectly use by by using the Numeric trait http://www.scala-lang.org/api/current/scala/math/Numeric.html