30

我有一个元组,想在不丢失类型安全的情况下添加一个元素。这就是我想要实现的目标:

val tuple = ("", 1, 1f) // (String, Int, Float)

val newTuple:(String, Int, Float, Double) = tuple :+ 1d
4

4 回答 4

19

无形现在做到了。添加

import shapeless.syntax.std.tuple._

在您的代码刚刚编译之前。

于 2014-07-19T19:02:11.200 回答
14

值得注意的是,您还可以用几行代码为此编写代码生成器:

val tupadd = for (n <- 2 to 20) yield {
  val t = (0 until n).map(i => ('A'+i).toChar).mkString(", ")
  val u = ('A'+n).toChar
  val i = (0 until n).map(i => "x._"+(i+1)).mkString(", ")
  List(
    s"implicit class TupOps$n[$t](val x: ($t)) extends AnyVal {",
    s"  def :+[$u](y: $u) = ($i, y)",
    s"  def +:[$u](y: $u) = (y, $i)",
    "}"
  ).mkString("\n")
}

把这些打印出来,把它们粘在一个文件里,你就可以开始了:

scala> implicit class TupOps2[A, B](val x: (A, B)) extends AnyVal {
     |   def :+[C](y: C) = (x._1, x._2, y)
     |   def +:[C](y: C) = (y, x._1, x._2)
     | }
defined class TupOps2

scala> (1,"salmon") :+ true
res15: (Int, String, Boolean) = (1,salmon,true)
于 2013-03-11T22:34:37.317 回答
9

我在很棒的Shapeless 库的帮助下找到了一个解决方案,它是HList

/*
  Define an implicit class to add the methods
  It accepts any tuple as we have typed it as Product
*/
implicit class TupleOps[A <: Product](t: A) {

  /*
    Declare the method to append

    B - The type of element we want to append
    L - The HList representing the tuple A
    P - The HList after appending B
    R - The final result
  */
  def :+[B, L <: HList, P <: HList, R <: Product](b: B)(
    /*
      We need some tools to help with the conversion

      hlister - Converts a tuple into an HList
      prepend - Can prepend one HList before another
      tupler  - Can convert an HList into a tuple
    */
    implicit hlister: HListerAux[A, L], prepend: PrependAux[L, B :: HNil, P], tupler: TuplerAux[P, R]):R =
      // Let the helpers do their job
      tupler(prepend(hlister(t), b :: HNil))

  /*
    The prepend method is similar to the append method but does not require
    the extra effort to append
  */
  def +:[B, L <: HList, R <: Product](b: B)(
    // Here we use the :: type of shapeless
    implicit hlister: HListerAux[A, L], tupler: TuplerAux[B :: L, R]):R =
      tupler(b :: hlister(t))
}

// usage is like this
("", 1, 1f) :+ 1d  //> res0: (String, Int, Float, Double) = ("",1,1.0,1.0)
1d +: ("", 1, 1f)  //> res1: (Double, String, Int, Float) = (1.0,"",1,1.0)

编辑

在某些情况下,当您需要处理隐式转换时,此解决方案无法与案例类结合使用。我现在恢复到以下实现(基于 Rex Kerr 的代码)

def char(n: Int) = ('A' + n).toChar
def prop(n: Int) = "t._" + (n + 1)

val result =
  for (n <- 1 to 21) yield {

    val range = (0 until n)
    val tupleTypeParams = range map char mkString ", "
    val tupleProperties = range map prop mkString ", "

    val elementType = char(n)
    val elementProperty = prop(n)

    val first = n == 1
    val tupleType = if (first) s"Tuple1[$tupleTypeParams]" else s"($tupleTypeParams)"
    val tupleInstance = if (first) s"Tuple1($tupleProperties)" else s"($tupleProperties)"

    val resultType = s"($tupleTypeParams, $elementType)"

    s"""|implicit def tupleOps$n[$tupleTypeParams, $elementType] = 
        |  new TupleAppendOps[$tupleType, $elementType, $resultType] {
        |    def append(t: $tupleType, e: $elementType) = ($tupleProperties, e)
        |    def init(t: $resultType) = $tupleInstance
        |    def last(t: $resultType) = $elementProperty
        |  }""".stripMargin
  }

println(result mkString "\n")
于 2013-03-11T21:54:11.883 回答
2

您可以在https://github.com/leonardschneider/macrogen上尝试基于宏天堂 scala 分支的实验性宏库,这正是您的示例。

现在我仍然有一些错误,我无法链接调用。

于 2013-03-12T11:46:32.493 回答