如何在Scala中实现通用数学函数 [英] How do I implement a generic mathematical function in Scala

查看:392
本文介绍了如何在Scala中实现通用数学函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用Scala,我认为应该很容易做到的事情却很难弄清楚.我正在尝试实现以下功能:

I'm just getting started with Scala and something which I think should be easy is hard to figure out. I am trying to implement the following function:

def square(x:Int):Int = { x * x }

这很好用,但是如果我想使此函数适用于任何类型的数字,我希望能够执行以下操作:

This works just fine, but if I want to try to make this function work for any kind of number I would like to be able to do the following:

def square[T <: Number](x : T):T = { x * x }

这抱怨并说:错误:值*不是类型参数T的成员

This complains and says: error: value * is not a member of type parameter T

我需要为此实现一个特征吗?

Do I need to implement a trait for this?

推荐答案

那是我在堆栈中的第一个问题之一溢出或大约Scala.问题在于Scala保持与Java的兼容性,这意味着它的基本数字类型等同于Java的基元.

That was one of my first questions in Stack Overflow or about Scala. The problem is that Scala maintains compatibility with Java, and that means its basic numeric types are equivalent to Java's primitives.

出现的问题是Java原语不是类,因此不具有允许数字"超类型的类层次结构.

The problem arises in that Java primitives are not classes, and, therefore, do not have a class hierarchy which would allow a "numeric" supertype.

简单地说,Java和Scala在Double+Int+之间看不到任何共同点.

To put it more plainly, Java, and, therefore, Scala, does not see any common grounds between a Double's + and a an Int's +.

Scala最终解决此限制的方法是使用所谓的 typeclass pattern 中的Numeric及其子类FractionalIntegral.基本上,您可以像这样使用它:

The way Scala finally got around this restriction was by using Numeric, and its subclasses Fractional and Integral, in the so-called typeclass pattern. Basically, you use it like this:

def square[T](x: T)(implicit num: Numeric[T]): T = {
    import num._
    x * x
}

或者,如果您不需要任何数字运算,但您需要调用的方法,则可以使用上下文绑定语法进行类型声明:

Or, if you do not need any of the numeric operations but the methods you call do, you can use the context bound syntax for type declaration:

def numberAndSquare[T : Numeric](x: T) = x -> square(x)

有关更多信息,请参阅我自己的问题中的答案.

For more information, see the answers in my own question.

这篇关于如何在Scala中实现通用数学函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆