дал следующую подпись для параметризованных методаScala параметризованных типа на 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 на последующие ING:
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)]
извинения, если я что-то очень очевидное отсутствует.
спасибо «DNA» и @mz, однако, 'def doubleBound [A <: Byte] (in: List [A]): List [A] = in.foldLeft (List.empty [A]) ((r, c) => (2 * c) .toByte.asInstanceOf [A] :: r) .реверсия val in = Список (1,2,3,4,5) println ("in" + in + "doubleBound ["+ doubleBound (in) +"] ")' все еще жалуется на 'error: аргументы inferred type [Int] не соответствуют методу параметра метода doubleBound [A <: Byte]' – cogitate
@cogitate «Int» не является 'Byte'. 'A' не может представлять' Int', если 'A' ограничено выше' Byte'. –
Попробуйте использовать фактический список 'Byte's:' List (1, 2, 3). map (_. toByte) ' –