【问题标题】:How to transform Array(e1, e2) into (e1, e2) using Scala 2.11.6 API only? [duplicate]如何仅使用 Scala 2.11.6 API 将 Array(e1, e2) 转换为 (e1, e2)? [复制]
【发布时间】:2015-05-10 12:30:57
【问题描述】:

给定:

scala> val ss = "hello_world".split("_")
ss: Array[String] = Array(hello, world)

如何将ss变成一个元组(hello, world),函数为Array(在ss上)?我正在考虑一个函数,所以上面的 sn-p 最终会变成 "hello_world".split("_").to[Tuple2] 或类似的。

是否可以仅使用 Scala 2.11.6 API?

【问题讨论】:

  • 我认为并不是真正的骗局
  • 为什么要这样做?如果您不知道拆分会产生多少元素,那么您就无法说明结果元组的类型。那么你会用它做什么呢?如果您正在寻找异构列表,请参阅 Shapeless 的 HList github.com/milessabin/shapeless
  • 有一些方法可以将列表转换为stackoverflow.com/questions/11305290/… 的元组。它们可用于将数组转换为以 array.toList 开头的元组。

标签: scala


【解决方案1】:

我能想到的最短的:

scala> "hello_world" split("_") match { case Array(f, s) => (f, s) }
res0: (String, String) = (hello,world)

当然它会抛出其他非Tuple2 的情况。您可以这样做以避免异常:

scala> "hello_world" split("_") match { case Array(f, s) => Some(f, s); case _ => None } 
res1: Option[(String, String)] = Some((hello,world))

或隐含:

scala> implicit class ArrayTupple[T](val a: Array[T]) { def pair = a match { case Array(f, s) => (f, s) } }
defined class ArrayTupple

scala> val ss = "hello_world".split("_")
ss: Array[String] = Array(hello, world)

scala> ss.pair
res0: (String, String) = (hello,world)

我仍然对解决方案不太满意。似乎您必须写出所有可能的情况,直到 Tuple22 以制作更通用的方法,例如 to[Tuple22] 或者可能使用宏。

【讨论】:

    【解决方案2】:

    不幸的是,没有可以将 N 个元素(当然是 N​​ Array 转换为 TupleN 的函数。有人提议对 Scala API[1] 进行更改,以将 :++: 方法添加到元组中,但它的优先级较低。人们在他们的项目中所做的事情基本上可以总结为一个 SO 问题 [2]。

    如果你按照他们的建议去做,并创建从TupleOps2 到 Tuple22 的类,这仍然是不可能的。看下面的代码:

    def array2Tuple[T](array: Array[T]): TupleN = {
      if(array.length == 2)
        (array(0), array(1))
      else
        array(0) +: array2Tuple(array.drop(1))
    }
    

    TupleN 返回类型中推导出N 仍然是不可能的。这里的问题当然是数组的大小与元组的大小。数组的大小包含在对象内部,而Tuple 的大小包含在类型名称中。

    参考文献:

    【讨论】:

      【解决方案3】:

      我不认为你可以做得更好

      "size_known".split("_") match { case Array(a, b) => (a, b) }
      

      Some("size_is_unknown".split("_")) collect { case Array(a, b) => (a, b) }
      

      无需重新发明Shapeless 的某些功能,即使其成为easy

      【讨论】:

        猜你喜欢
        • 2012-12-22
        • 2020-01-03
        • 1970-01-01
        • 2015-07-30
        • 1970-01-01
        • 2021-12-27
        • 1970-01-01
        • 1970-01-01
        • 2021-09-03
        相关资源
        最近更新 更多