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

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

问题描述

我现在正在尝试学习 Scala,在 Haskell 方面有一点经验.对我来说很奇怪的一件事是 Scala 中的所有函数参数 必须 使用类型进行注释——这是 Haskell 不需要的.为什么是这样?举个更具体的例子:一个 add 函数是这样写的:

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

但是,这只适用于双精度数(嗯,整数也适用,因为隐式类型转换).但是,如果您想定义自己的类型并定义自己的 + 运算符,该怎么办.您将如何编写适用于任何定义 + 运算符的类型的 add 函数?

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 使用 Hindley-Milner 类型推断算法,而 Scala 为了支持面向对象的一面,现在不得不放弃使用它.

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.

为了轻松为所有适用类型编写添加函数,您需要使用 Scala 2.8.0:

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天全站免登陆