Scala mergeMsg与def

时间:2017-10-19 11:18:07

标签: scala

我必须写一个mergeMsg函数。

该功能应具有以下签名

((String, String, Double), (String, String, Double)) => (String, String, Double)

在某种程度上,前元组的每个对象都应该添加到后一个元组的相应对象中。

我怎么写这个?

2 个答案:

答案 0 :(得分:4)

最简单的方法是使用CatsMonoids

scala> import cats.implicits._
import cats.implicits._

scala> type Tup = (String, String, Double)
defined type alias Tup

scala> def mergeMsg(a: Tup, b: Tup): Tup = a |+| b 
mergeMsg: (a: Tup, b: Tup)Tup

scala> mergeMsg(("Hello", "World", 4.5), (" John", " Cup", 25.5))
res0: Tup = (Hello John,World Cup,30.0)

当然,您不需要定义类型别名Tup,它只会缩短它。

答案 1 :(得分:0)

不那么灵活,但没有额外的库依赖:

  type Tpl[T, V] = (T, T, V)
  type Sum[T] = (T, T) => T

  def mergeMsg[T, V](first: Tpl[T, V], second: Tpl[T, V])(implicit tSum: Sum[T], vSum: Sum[V]): Tpl[T, V] =
    (tSum(first._1, second._1), tSum(first._2, second._2), vSum(first._3, second._3))

  implicit val intSum: Sum[Int] = _ + _
  implicit val strSum: Sum[String] = _ concat _

  println(mergeMsg((1, 2, "Hello"), (2, 3, "World")))