如何在 Scala 中将元素附加或前置到元组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15349439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 05:03:08  来源:igfitidea点击:

How to append or prepend an element to a tuple in Scala

scalashapeless

提问by EECOLOR

I have a tuple and want to add an element without loosing type safety. This is what I want to achieve:

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

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

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

采纳答案by Rex Kerr

It's worth noting that you can also write a code generator for this in a few lines:

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

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

Print these out, stick 'em in a file, and you're good to go:

打印出来,把它们放在一个文件中,你就可以开始了:

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)

回答by Alex Archambault

Shapeless now does it. Adding

无形现在做到了。添加

import shapeless.syntax.std.tuple._

before your code just compiles.

在您的代码编译之前。

回答by EECOLOR

I found a solution with the help of the awesome Shapeless libraryand it's HList

我在很棒的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)

Edit

编辑

In some cases, where you need to deal with implicit conversions this solution will not work in combination with case classes. I now reverted to the following implementation (based on the code of Rex Kerr)

在某些情况下,您需要处理隐式转换,此解决方案无法与案例类结合使用。我现在恢复到以下实现(基于 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")

回答by Leo

You can try my experimental macros library based on macro paradise scala branch at https://github.com/leonardschneider/macrogenwhich does exactly your example.

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

Right now I still have some bugs though, where I can not chain the calls.

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