您的代码存在一些问题:
- 一般来说,您不能对不受约束的泛型类型执行算术运算;不知何故,您必须传达任何支持的算术运算。
- 乘以 1 通常不会产生任何影响。
- 如前所述,您不要使用方括号声明
List 实例(它们用于声明泛型类型参数)。
- 您传递给
multiply 的参数是两个单独的列表(使用无效的分号分隔符而不是逗号),而不是列表列表。
- 在
if 子句中,返回值为Nil,它与声明的返回类型List[List[A]] 匹配。然而,else 子句试图执行一个计算,该计算将List 实例(不是列表的内容)乘以一个 Int。即使这是有道理的,结果类型显然不是List[List[A]]。 (这也让我很难准确理解您要完成的工作。)
假设您尝试将内部列表的每个成员乘以特定因子,以下是更正上述代码的版本:
// Multiply every element in a list of lists by the specified factor, returning the
// resulting list of lists.
//
// Should work for any primitive numeric type (Int, Double, etc.). For custom value types,
// you will need to declare an `implicit val` of type Numeric[YourCustomType] with an
// appropriate implementation of the `Numeric[T]` trait. If in scope, the appropriate
// num value will be identified by the compiler and passed to the function automatically.
def multiply[A](ll: List[List[A]], factor: A)(implicit num: Numeric[A]): List[List[A]] = {
// Numeric[T] trait defines a times method that we use to perform the multiplication.
ll.map(_.map(num.times(_, factor)))
}
// Sample use: Multiply every value in the list by 5.
val tt = multiply(List(List(3, 4, 5, 6), List(4, 5, 6, 7, 8)), 5)
println(tt)
这应该会产生以下输出:
List(List(15, 20, 25, 30), List(20, 25, 30, 35, 40))
但是,您可能只是想将列表中的所有值相乘。这实际上更简单一些(注意不同的返回类型):
def multiply[A](ll: List[List[A]])(implicit num: Numeric[A]): A = ll.flatten.product
// Sample use: Multiply all values in all lists together.
val tt = multiply(List(List(3, 4, 5, 6), List(4, 5, 6, 7, 8)))
println(tt)
这应该会产生以下输出:
2419200
我建议你阅读一本关于 Scala 的好书。这些例子中有很多非常复杂的东西,在这里解释它们需要很长时间。 Odersky, Spoon & Venners 的 Programming in Scala, Third Edition 是一个好的开始。这将涵盖List[A] 操作,例如map、flatten 和product 以及implicit 函数参数和implicit val 声明。