有没有办法从列表中创建元组(没有代码生成)?

时间:2012-07-03 06:02:43

标签: scala tuples iterable-unpacking

有时需要从小型集合中创建元组(例如,烫伤框架)。

def toTuple(list:List[Any]):scala.Product = ...

6 个答案:

答案 0 :(得分:15)

你真的不希望你的方法返回Product,因为这是无用的模糊。如果你想能够将返回的对象用作元组,那么你必须知道它的arity。所以你可以做的是为不同的arities提供一系列toTupleN方法。为方便起见,您可以在Seq上将这些方法添加为隐式方法。

这个怎么样:

class EnrichedWithToTuple[A](elements: Seq[A]) {
  def toTuple2 = elements match { case Seq(a, b) => (a, b) }
  def toTuple3 = elements match { case Seq(a, b, c) => (a, b, c) }
  def toTuple4 = elements match { case Seq(a, b, c, d) => (a, b, c, d) }
  def toTuple5 = elements match { case Seq(a, b, c, d, e) => (a, b, c, d, e) }
}
implicit def enrichWithToTuple[A](elements: Seq[A]) = new EnrichedWithToTuple(elements)

并使用它:

scala> List(1,2,3).toTuple3
res0: (Int, Int, Int) = (1,2,3)

答案 1 :(得分:14)

如果像@dhg观察到的那样,你预先知道预期的arity,你可以在这里做一些有用的事情。使用shapeless你可以写,

scala> import shapeless._
import shapeless._

scala> import Traversables._
import Traversables._

scala> import Tuples._
import Tuples._

scala> List(1, 2, 3).toHList[Int :: Int :: Int :: HNil] map tupled
res0: Option[(Int, Int, Int)] = Some((1,2,3))

答案 2 :(得分:9)

如果你事先不知道arity并想做一个可怕的糟糕黑客攻击,你可以这样做:

def toTuple[A <: Object](as:List[A]):Product = {
  val tupleClass = Class.forName("scala.Tuple" + as.size)
  tupleClass.getConstructors.apply(0).newInstance(as:_*).asInstanceOf[Product]
}
toTuple: [A <: java.lang.Object](as: List[A])Product

scala> toTuple(List("hello", "world"))
res15: Product = (hello,world)

答案 3 :(得分:3)

您想要Tuple还是仅Product。因为这封信:

case class SeqProduct[A](elems: A*) {
  override def productArity: Int = elems.size
  override def productElement(i: Int) = elems(i)
}

SeqProduct(List(1, 2, 3): _*)

答案 4 :(得分:1)

基于@Kim Stebel的想法,我写了一个简单的实用程序,它从seq创建元组。

import java.lang.reflect.Constructor

/**
 * Created by Bowen Cai on 1/24/2015.
 */
sealed trait Product0 extends Any with Product {

  def productArity = 0
  def productElement(n: Int) = throw new IllegalStateException("No element")
  def canEqual(that: Any) = false
}
object Tuple0 extends Product0 {
  override def toString() = "()"
}

case class SeqProduct(elems: Any*) extends Product {
  override def productArity: Int = elems.size
  override def productElement(i: Int) = elems(i)
  override def toString() = elems.addString(new StringBuilder(elems.size * 8 + 10), "(" , ",", ")").toString()
}

object Tuples {

  private[this] val ctors = {
    val ab = Array.newBuilder[Constructor[_]]
    for (i <- 1 to 22) {
      val tupleClass = Class.forName("scala.Tuple" + i)
      ab += tupleClass.getConstructors.apply(0)
    }
    ab.result()
  }

  def toTuple(elems: Seq[AnyRef]): Product = elems.length match {
    case 0 => Tuple0
    case size if size <= 22 =>
      ctors(size - 1).newInstance(elems: _*).asInstanceOf[Product]
    case size if size > 22 => new SeqProduct(elems: _*)
  }

}

答案 5 :(得分:0)

scala> val numbers = Seq(1,2,4)
numbers: Seq[Int] = List(1, 2, 4)

scala> val string = numbers.mkString("(",",",")")
string: String = (1,2,4)

*** mkString(start:String, sep: String, end: String)

我在子句中生成了它。