Scala:如何定义“通用”函数参数? [英] Scala: How to define "generic" function parameters?
问题描述
def add(x:Double, y:Double)= x + y
但是,这只适用于双打由于隐式类型转换)。但是如果你想定义自己的类型来定义自己的 + 运算符,会发生什么呢?你将如何编写一个add函数,该函数适用于定义 + 运算符的任何类型?
Haskell使用Hindley-Milner类型推理算法,而Scala为了支持面向对象的事物,现在不得不放弃使用它。
为了编写一个add函数适用于所有适用类型,您将需要使用Scala 2.8.0:
欢迎使用Scala 2.8.0.r18189 -b20090702020221(Java HotSpot TM 64位服务器VM,Java 1.6.0_15)。
键入表达式让他们评估。
输入:help获取更多信息。
scala> import Numeric._
import Numeric._
scala> def add [A](x:A,y:A)(隐式数字:数字[A]):A =
|数字.plus(x,y)
add:[A](x:A,y:A)(隐式数字:数字[A])A
scala> add(1,2)
res0:Int = 3
scala>添加(1.1,2.2)
res1:Double = 3.3000000000000003
I am trying to learn Scala now, with a little bit of experience in Haskell. One thing that stood out as odd to me is that all function parameters in Scala must be annotated with a type - something that Haskell does not require. Why is this? To try to put it as a more concrete example: an add function is written like this:
def add(x:Double, y:Double) = x + y
But, this only works for doubles(well, ints work too because of the implicit type conversion). But what if you want to define your own type that defines its own + operator. How would you write an add function which works for any type that defines a + operator?
Haskell uses Hindley-Milner type inference algorithm whereas Scala, in order to support Object Oriented side of things, had to forgo using it for now.
In order to write an add function for all applicable types easily, you will need to use Scala 2.8.0:
Welcome to Scala version 2.8.0.r18189-b20090702020221 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_15).
Type in expressions to have them evaluated.
Type :help for more information.
scala> import Numeric._
import Numeric._
scala> def add[A](x: A, y: A)(implicit numeric: Numeric[A]): A =
| numeric.plus(x, y)
add: [A](x: A,y: A)(implicit numeric: Numeric[A])A
scala> add(1, 2)
res0: Int = 3
scala> add(1.1, 2.2)
res1: Double = 3.3000000000000003
这篇关于Scala:如何定义“通用”函数参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!