在 Scala 中实现测量值 [英] Implementing a Measured value in Scala
问题描述
测量值由(通常为非负)浮点数和测量单位组成.关键是要表示现实世界的数量,以及管理它们的规则.举个例子:
A Measured value consists of (typically nonnegative) floating-point number and unit-of-measure. The point is to represent real-world quantities, and the rules that govern them. Here's an example:
scala> val oneinch = Measure(1.0, INCH)
oneinch : Measure[INCH] = Measure(1.0)
scala> val twoinch = Measure(2.0, INCH)
twoinch : Measure[INCH] = Measure(2.0)
scala> val onecm = Measure(1.0, CM)
onecm : Measure[CM] = Measure(1.0)
scala> oneinch + twoinch
res1: Measure[INCH] = Measure(3.0)
scala> oneinch + onecm
res2: Measure[INCH] = Measure(1.787401575)
scala> onecm * onecm
res3: Measure[CMSQ] = Measure(1.0)
scala> onecm * oneinch
res4: Measure[CMSQ] = Measure(2.54)
scala> oncem * Measure(1.0, LITER)
console>:7: error: conformance mismatch
scala> oneinch * 2 == twoinch
res5: Boolean = true
在你太兴奋之前,我还没有实现这个,我只是虚构了一个 REPL 会话.我什至不确定语法,我只是希望能够处理诸如添加测量数量(即使是混合单位)、乘以测量数量等等之类的事情,理想情况下,我喜欢 Scala 引以为豪的类型系统来保证在编译时,表达式是有意义的.
Before you get too excited, I haven't implemented this, I just dummied up a REPL session. I'm not even sure of the syntax, I just want to be able to handle things like adding Measured quantities (even with mixed units), multiplying Measured quantities, and so on, and ideally, I like Scala's vaunted type-system to guarantee at compile-time that expressions make sense.
我的问题:
- 这个问题有现存的术语吗?
- 这已经在 Scala 中完成了吗?
- 如果不是,我将如何表示长度"和以米为单位的长度"等概念?
- 这是用其他语言完成的吗?
价值 3.3 亿美元的火星探测器丢失,因为承包商使用码和磅,NASA 使用米和牛顿.Measure 库可以防止崩溃.
A $330-million Mars probe was lost because the contractor was using yards and pounds and NASA was using meters and newtons. A Measure library would have prevented the crash.
推荐答案
嗯,这个功能存在于 Java 中,这意味着你可以直接在 Scala 中使用它.
Well, this functionality exists in Java, meaning you can use it directly in Scala.
jsr-275,已移至 谷歌代码.jscience 实现了规范.这是一个很好的介绍.如果你想要一个更好的界面,我会以此为基础并围绕它构建一个包装器.
jsr-275, which was moved to google code. jscience implements the spec. Here's a good introduction. If you want a better interface, I'd use this as a base and build a wrapper around it.
这篇关于在 Scala 中实现测量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!