gpt4 book ai didi

Scala:Seq[T] 元素的功能聚合 => Seq[Seq[T]](保留顺序)

转载 作者:行者123 更新时间:2023-12-04 16:40:56 26 4
gpt4 key购买 nike

我想在一个序列中聚合兼容的元素,即转换 Seq[T]Seq[Seq[T]]其中每个子序列中的元素彼此兼容,同时保留原始 seq 顺序,例如从

case class X(i: Int, n: Int) {
def canJoin(that: X): Boolean = this.n == that.n
override val toString = i + "." + n
}
val xs = Seq(X(1, 1), X(2, 3), X(3, 3), X(4, 3), X(5, 1), X(6, 2), X(7, 2), X(8, 1))
/* xs = List(1.1, 2.3, 3.3, 4.3, 5.1, 6.2, 7.2, 8.1) */

想要得到
val js = join(xs)
/* js = List(List(1.1), List(2.3, 3.3, 4.3), List(5.1), List(6.2, 7.2), List(8.1)) */

我试图以一种功能性的方式做到这一点,但我中途被卡住了:

使用 while 循环
def split(seq: Seq[X]): (Seq[X], Seq[X]) = seq.span(_ canJoin seq.head)
def join(seq: Seq[X]): Seq[Seq[X]] = {
var pp = Seq[Seq[X]]()
var s = seq
while (!s.isEmpty) {
val (p, r) = split(s)
pp :+= p
s = r
}
pp
}

split我很满意,但 join似乎有点太长了。

在我看来,这是一项标准任务。这让我想到了一个问题:
  • 中是否有函数馆藏图书馆这使得它
    可以减少代码大小吗?
  • 或者是否有不同的方法来解决任务?尤其是另一个
    方法比Rewriting a sequence by partitioning and collapsing ?

  • 用尾递归替换while循环
    def join(xs: Seq[X]): Seq[Seq[X]] = {
    @annotation.tailrec
    def jointr(pp: Seq[Seq[X]], rem: Seq[X]): Seq[Seq[X]] = {
    val (p, r) = split(rem)
    val pp2 = pp :+ p
    if (r.isEmpty) pp2 else jointr(pp2, r)
    }
    jointr(Seq(), xs)
    }

    最佳答案

    def join(seq: Seq[X]): Seq[Seq[X]] = {
    if (seq.isEmpty) return Seq()
    val (p,r) = split(seq)
    Seq(p) ++ join(r)
    }

    关于Scala:Seq[T] 元素的功能聚合 => Seq[Seq[T]](保留顺序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8086158/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com