中实现通用数学函数

中实现通用数学函数

本文介绍了如何在 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

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

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

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

Do I need to implement a trait for this?

推荐答案

那是我在 Stack 中的第一个问题溢出或关于 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 最终绕过这个限制的方法是使用 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
}

或者,如果您不需要任何数字操作,但您调用的方法需要,您可以使用 context bound 语法进行类型声明:

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 中实现通用数学函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 03:55