Scala 中以案例类作为键的高效映射?
以下 C 代码使用枚举和数组作为从枚举到任何内容的高效“映射”:
enum Color { ColorRed, ColorGreen, ColorBlue, ColorSize};
void f() {
int x[ColorSize];
x[ColorRed] = 12;
x[ColorGreen] = 33;
x[ColorBlue] = 4;
return x[ColorGreen];
}
这对于 Scala 来说可能吗?
即有一个从案例类到某事物的“映射”,以高效数组而不是树或散列图的形式实现。然而我希望能够仅使用特定类型而不是 Int 进行索引。
更新:简而言之,我希望 Scala 数组能够通过某种枚举(案例类或枚举)进行索引。
A following C code uses enum and array as efficient "map" from enum to anything:
enum Color { ColorRed, ColorGreen, ColorBlue, ColorSize};
void f() {
int x[ColorSize];
x[ColorRed] = 12;
x[ColorGreen] = 33;
x[ColorBlue] = 4;
return x[ColorGreen];
}
Is this possible with Scala?
I.e. to have a "map" from case class to something, implemented as efficient array and not as tree or as hashmap. Yet I would like to be able to index only with a paricular type not with Int.
Update: In short I would like to have Scala Array indexed by some kind of enum (case class or Enumeration).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于小型枚举,您可以“模拟”C 行为:
但是,我怀疑这是否会被认为是好的风格,特别是因为它不安全。使用地图是更好的方法,或者您可以将数组包装在处理颜色索引的专用数据结构中:
For small enumerations you can "simulate" the C behavior:
However, I doubt this would be considered good style, especially because it's unsafe. Using a map is a better approach, or you could wrap an array in a specialized data structure which deals with Color indizes:
如果你想要完整的 C 性能,你可以这样做:
它与 C & 中的方法同样不安全。一样高效。然而,这是非常不安全的。
If you want the full C performance you could do this:
It's equally unsafe as the method in C & just as performant. It is however very unsafe.