1, "a" -> 2, "b" -> 3, "c" -> 4, "c" -> 5) implicit c-6ren">
gpt4 book ai didi

scala - 关于给定谓词多次拆分的集合方法的思考

转载 作者:行者123 更新时间:2023-12-04 04:38:20 24 4
gpt4 key购买 nike

我正在寻找一种在给定的成对条件下拆分的集合方法,例如

val x = List("a" -> 1, "a" -> 2, "b" -> 3, "c" -> 4, "c" -> 5)

implicit class RichIterableLike[A, CC[~] <: Iterable[~]](it: CC[A]) {
def groupWith(fun: (A, A) => Boolean): Iterator[CC[A]] = new Iterator[CC[A]] {
def hasNext: Boolean = ???

def next(): CC[A] = ???
}
}

assert(x.groupWith(_._1 != _._1).toList ==
List(List("a" -> 1, "a" -> 2), List("b" -> 3), List("c" -> 4, "c" -> 5))
)

所以这是一种递归 span .

虽然我能够实现 ??? ,我想知道
  • 如果我正在监督的收藏中已经存在某些东西
  • 应该调用什么方法; groupWith听起来不对。它应该简洁,但不知何故反射(reflect)了函数参数对对进行操作。 groupWhere我想会更接近一些,但仍然不清楚。
  • 实际上我猜在使用 groupWith 时,谓词逻辑应该反转,所以我会使用 x.groupWith(_._1 == _._1)
  • 关于类型的想法。返回 Iterator[CC[A]]对我来说看起来很合理。也许它需要一个 CanBuildFrom并返回 Iterator[To] ?
  • 最佳答案

    您还可以编写一个使用 tailrec/pattern 匹配的版本:

      def groupWith[A](s: Seq[A])(p: (A, A) => Boolean): Seq[Seq[A]] = {
    @tailrec
    def rec(xs: Seq[A], acc: Seq[Seq[A]] = Vector.empty): Seq[Seq[A]] = {
    (xs.headOption, acc.lastOption) match {
    case (None, _) => acc
    case (Some(a), None) => rec(xs.tail, acc :+ Vector(a))
    case (Some(a), Some(group)) if p(a, group.last) => rec(xs.tail, acc.init :+ (acc.last :+ a))
    case (Some(a), Some(_)) => rec(xs.tail, acc :+ Vector(a))
    }
    }

    rec(s)
    }

    关于scala - 关于给定谓词多次拆分的集合方法的思考,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19348062/

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