Scala:如何定义“通用”函数参数? [英] Scala: How to define "generic" function parameters?

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

问题描述

现在我正在尝试学习Scala,并且在Haskell有一些经验。有一件事对我来说很奇怪,那就是Scala中的所有函数参数都必须用类型注释 - 这是Haskell不需要的。为什么是这样?试图把它作为一个更具体的例子:一个添加函数是这样写的:

  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屋!

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