[英]scala parameterized type on foldLeft
给定参数化方法的以下签名
def double[A <: Byte](in:List[A]): List[A] = {
//double the values of the list using foldLeft
//for ex. something like:
in.foldLeft(List[A]())((r,c) => (2*c) :: r).reverse
//but it doesn't work! so..
}
在解决参数化类型的foldLeft之前,我尝试获取以下内容
def plainDouble[Int](in:List[Int]): List[Int] = {
in.foldLeft(List[Int]())((r:List[Int], c:Int) => {
var k = 2*c
println("r is ["+r+"], c is ["+c+"]")
//want to prepend to list r
// k :: r
r
})
}
但是,这导致以下错误:
$scala fold_ex.scala
error: overloaded method value * with alternatives:
(x: Double)Double <and>
(x: Float)Float <and>
(x: Long)Long <and>
(x: scala.Int)scala.Int <and>
(x: Char)scala.Int <and>
(x: Short)scala.Int <and>
(x: Byte)scala.Int
cannot be applied to (Int(in method plainDouble))
val k = 2*c
^
one error found
如果我将def的签名更改为以下内容:
def plainDouble(in:List[Int]): List[Int] = { ...}
的作品和输出为:
val in = List(1,2,3,4,5)
println("in "+ in + " plainDouble ["+plainDouble(in)+"]")
是
in List(1, 2, 3, 4, 5) plainDouble [List(2, 4, 6, 8, 10)]
抱歉,如果我错过了一些非常明显的内容。
问题是一种名称隐藏:
def plainDouble[Int](in:List[Int]): List[Int] = {
^^^
// this is a type parameter called "Int"
您在声明一个名为Int
的类型变量的同时,还尝试使用具体类型Int
,这会引起混乱。 例如,如果删除类型变量(因为它实际上并未使用)或将其重命名为I
,则代码将编译。
@DNA是正确的,因为plainDouble[Int]
声明了一个名为Int
的类型参数,该参数与实际类型无关。 因此,您尝试使其非通用实际上仍然是通用的,但是这种方式并不很快。
但是最初的问题呢?
scala> def double[A <: Byte](in: List[A]): List[A] = in.foldLeft(List.empty[A])((r,c) => (2*c) :: r)
<console>:15: error: type mismatch;
found : x$1.type (with underlying type Int)
required: A
def double[A <: Byte](in: List[A]): List[A] = in.foldLeft(List.empty[A])((r,c) => (2*c) :: r).reverse
^
这里的问题是2 * c
是一个Int
,而不是A
Int
上的*(byte: Byte)
方法返回另一个Int
。 因此,消息(with underlying type Int)
。 请注意,如果强制转换为A
,它将编译:
def double[A <: Byte](in: List[A]): List[A] =
in.foldLeft(List.empty[A])((r,c) => (2*c).toByte.asInstanceOf[A] :: r).reverse
注意在转换为A
之前我还必须调用toByte
。 这并不是泛型在工作中的一个光辉的例子,但重点是不兼容的返回类型正在导致错误。
还要注意,如果删除2 *
它不会发生:
def double[A <: Byte](in: List[A]): List[A] =
in.foldLeft(List.empty[A])((r,c) => c :: r).reverse
编辑:
您可能会考虑对此类泛型使用Numeric
特征。
import scala.math.Numeric.Implicits._
def double[A: Numeric](in: List[A])(implicit i2a: Int => A): List[A] =
in.map(_ * 2)
这依赖于隐式的Numeric[A]
可用于您的数字类型( scala.math.Numeric
对象中存在该scala.math.Numeric
,几乎是您想要的任何数字类型)。 它还依赖于从Int
到A
的隐式转换,以便我们可以编写a * 2
。 我们可以使用+
代替此约束:
def double[A: Numeric](in: List[A]): List[A] = in.map(a => a + a)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.