类型参数化算术?
试着想办法把 2 小时减去 5 分钟。
从 2 减去 5 没有意义,因为我们最终得到 -3 个通用时间单位,这是无用的。但如果“小时”是“分钟”的子类型,我们可以将 2 小时转换为 120 分钟,得到 115 分钟,即 1 小时 55 分钟。
同样,如果我们想将 5 个苹果加到 5 个橙子中,我们不能用苹果来评估,但可能会期望最终得到 10 个水果。
从上面的例子来看,通常当使用数字作为形容词时,整数需要通过它们描述的对象类型来参数化。 而不是声明,那么这将非常有用
val hours = 2
val minutes = 5
我认为,如果您可以做一些类似的事情,
val hours = 2[Hour]
val minutes = 5[Minute]
val result = hours - minutes
assert (result == 115[Minute])
,这样的事情是否存在,它会有用吗?它是否可以实现?
编辑:澄清一下,上面的时间示例只是我想出的一个随机示例。我的问题更多的是,一般来说,参数化数值的想法是否是一个有用的概念,就像参数化列表等一样。(答案可能是“否”,我不知道!)
Trying to think of a way to subtract 5 minutes from 2 hours.
It doesn't make sense to subtract 5 from 2, because we end up with -3 generic time units, which is useless. But if "hour" is a subtype of "minute", we could convert 2 hours to 120 minutes, and yield 115 minutes, or 1 hour and 55 minutes.
Similarly, if we want to add 5 apples to 5 oranges, we cannot evaluate this in terms of apples, but might expect to end up with 10 fruit.
It seems in the above examples, and generally when using a number as an adjective, the integers need to be parameterized by the type of object they describing. I think it would be very useful if instead of declaring
val hours = 2
val minutes = 5
you could do something like
val hours = 2[Hour]
val minutes = 5[Minute]
val result = hours - minutes
assert (result == 115[Minute])
Does anything like this exist, would it be useful, and is it something that could be implemented?
EDIT: to clarify, the time example above is just a random example I thought up. My question is more whether in general the idea of parameterized Numerics is a useful concept, just as you have parameterized Lists etc. (The answer might be "no", I don't know!)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以通过使用两个小时和分钟类以及从小时到分钟的隐式转换函数来完成此操作
这允许您执行类似的操作
You can accomplish this by having two classes for Hours and Minutes, along with an implicit conversion function from hours to minutes
This allows you to do something like
您可以在 lift 框架中找到一些示例(规范)。
(注:看来你需要有合理的数字才能正确比较。例如,可能不超过 60 秒。)
You can find some examples for this in the lift framework (spec).
(Note: it seems you need to have reasonable numbers for correct comparison. Eg. There may be no more than 60 seconds.)
您可以尝试 scala-time,它是 Joda Time 并使其对于 Scala 来说更加惯用,包括一些 DSL 来进行时间段计算,类似于 Brian Agnew 在他的回答。
例如,
创建一个 Joda
Period
。You might try scala-time, which is a wrapper around Joda Time and makes it a bit more idiomatic for Scala, including some DSL to do time period computations, similar to what Brian Agnew suggested in his answer.
For instance,
creates a Joda
Period
.在我看来,DSL 在这里很有用。因此,您可以编写
并进行适当的转换,将 2 小时转换为 Hours 对象(值 2)等。
有大量资源描述 Scala 的 DSL 功能。例如 请参阅 O'Reilly
It seems to me a DSL would be of use here. So you could write
and the appropriate conversions would take place to convert 2 hours into a Hours object (value 2) etc.
Lots of resources exist describing Scala's DSL capabilities. e.g. see this from O'Reilly