scala - 将泛型类的每个元素相乘
问题描述
我有一个泛型类,它包含一个类型 T 的列表,并且我有连接两个对象并返回新对象的方法“concat”。我需要让它连接两个列表,但是如果列表的类型是 Int、Double 或 Float,它应该将列表的每个元素乘以 func 的结果
class Seq[T : Ordering] (initialElems: T*)(implicit toStr: ToStr[T]) {
override def toString: String = toStr(fac(factors), elems: _*)
val elems = initialElems.sorted
def concat(a:Seq[T]) = new Seq(a.elems ++ this.elems:_*)
val factors = ListBuffer[Int](1)
def fac(xs: ListBuffer[Int]): Int = {
var i=0
var sum = 1
while (i < xs.length) {
sum *= xs(i)
i += 1
}
sum
}
def multy(a: Int)(implicit ev: T <:< AnyVal): Unit = {
factors += a
}
}
trait ToStr[T] {
def apply(fac: Int, elems: T*): String
}
object ToStr {
implicit val int: ToStr[Int] =
(fac, elems) => elems.map((i: Int) => fac * i).toString
implicit val double: ToStr[Double] =
(fac, elems) => elems.map((i: Double) => fac * i).toString
implicit val float: ToStr[Float] =
(fac, elems) => elems.map((i: Float) => fac * i).toString
implicit val str: ToStr[String] = (_, elems) => elems.toString
}
例如我创建两个列表
val numbers1 = new Seq(1,5,4,2)
val numbers2 = new Seq(7,8,11,17)
比我添加因素
number1: numbers1.multy(5)
numbers1.multy(3)
和因素
number2: numbers2.multy(10)
在我 concat 之后number = number1.concat(numbers2)
,我希望得到包含的数字
(1*3*5, 5*3*5, 4*3*5, 2*3*5, 7*10, 8*10, 11*10, 17*10)
(排序后将是)->
(15, 30, 60, 70, 75, 80, 110, 170)
如果字符串列表不应该相乘而只是连接。例如
strings1 = new Seq("b", "e", "f")
strings2 = new Seq("c", "a")
strings = strings1.concat(strings2)
字符串将是("a", "b", "c", "e", "f")
如何更改方法 concat 以这种方式工作?
解决方案
pattern matching
例如,我会尝试guard conditions
:
def concat[A](a: Seq[A]) = {
a match {
case(h::_) if h.isInstanceOf[Int] => // do multiply and return as ....
case(h::_) if h.isInstanceOf[String] => // do concat and return as ....
case _ => throw new NoSuchElementException
}
}
推荐阅读
- java - 如何在下面的代码中模拟遗留对象?
- bash - 在bash中将十六进制转换为十进制
- google-bigquery - 分区表中未分区的旧行
- node.js - 如何在 Mongoose 中对类别进行分组
- typescript - 如何避免在 Typescript 中分布多个泛型类型参数?
- ag-grid - AgGridReact:使用侧边栏时将水平滚动放在底部
- android - 在 Android 应用程序中将 geojson 文件添加到我的地图
- c# - C# Selenium Firefox 驱动程序设置 navigator.webdriver = false
- xml - bcp 命令未在格式文件中定义可空值
- centos - 旋转异常日志的 logrotate 问题