【问题标题】:Scala mergeMsg with defScala mergeMsg 与 def
【发布时间】:2017-10-19 11:18:06
【问题描述】:

我必须写一个mergeMsg 函数。

该函数应具有以下签名

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

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

我该怎么写?

【问题讨论】:

  • 不清楚你要做什么......你能举个例子吗?

标签: scala


【解决方案1】:

最简单的就是使用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 为Monoid!只是想注意,可以定义Monoid[String] 的自定义实例,以便使用" " 而不是默认行为进行连接。
  • 顺便说一句,这甚至不是 Monoid,可能只是一个 Semigroup 就足够了 :)
  • 是的,空格会违反身份法:)
【解决方案2】:

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

  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")))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-27
    • 2020-03-04
    • 1970-01-01
    • 1970-01-01
    • 2010-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多