Scala:实现 Numeric 的子类型[T]

发布于 2024-08-21 23:01:02 字数 85 浏览 3 评论 0原文

如何实现 Numeric[T] 的子类型? 我一直在寻找这方面的指南,但没有找到。 子类型的示例可以是理性的还是复杂的?

提前致谢 特罗尔斯

How does one go about implementing a subtype of Numeric[T]?
I have been looking for at guide on this but haven't found any.
Example of subtypes could be Rational or Complex?

Thanks in advance
Troels

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我的鱼塘能养鲲 2024-08-28 23:01:02

一个绝对无用的字符串数字:

trait StringIsNumeric extends Numeric[String] {
  def plus(x: String, y: String): String = "%s+%s" format (x, y)
  def minus(x: String, y: String): String = "%s-%s" format (x)
  def times(x: String, y: String): String = "%s*%s" format (x, y)
  def quot(x: String, y: String): String = "%s/%s" format (x, y)
  def rem(x: String, y: String): String =  "%s%%s" format (x, y)
  def negate(x: String): String = "-%s" format (x)
  def fromInt(x: Int): String = x.toString
  def toInt(x: String): Int = 0
  def toLong(x: String): Long = 0L
  def toFloat(x: String): Float = 0.0f
  def toDouble(x: String): Double = 0.0
}
implicit object StringIsNumeric extends StringIsNumeric with Ordering.StringOrdering


def x[T: Numeric](t1 : T, t2 : T)  = {
  val n = implicitly[Numeric[T]]
  import n._
  t1 * t2
}
scala> x("a","b")
res0: java.lang.String = a*b

An absolutely useless String Numeric:

trait StringIsNumeric extends Numeric[String] {
  def plus(x: String, y: String): String = "%s+%s" format (x, y)
  def minus(x: String, y: String): String = "%s-%s" format (x)
  def times(x: String, y: String): String = "%s*%s" format (x, y)
  def quot(x: String, y: String): String = "%s/%s" format (x, y)
  def rem(x: String, y: String): String =  "%s%%s" format (x, y)
  def negate(x: String): String = "-%s" format (x)
  def fromInt(x: Int): String = x.toString
  def toInt(x: String): Int = 0
  def toLong(x: String): Long = 0L
  def toFloat(x: String): Float = 0.0f
  def toDouble(x: String): Double = 0.0
}
implicit object StringIsNumeric extends StringIsNumeric with Ordering.StringOrdering


def x[T: Numeric](t1 : T, t2 : T)  = {
  val n = implicitly[Numeric[T]]
  import n._
  t1 * t2
}
scala> x("a","b")
res0: java.lang.String = a*b
笑梦风尘 2024-08-28 23:01:02

我添加了 Real 到 Scalaz,具有实例 Real[Double]Real[Dual]

我发现使 fromDouble 隐式化很方便

I added Real to Scalaz, with instances Real[Double] and Real[Dual].

I found it convenient to make fromDouble implicit

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文