【问题标题】:Find Indexes *Where*查找索引*在哪里*
【发布时间】:2013-10-30 01:41:25
【问题描述】:

Vector 中有一个 indexWhere 函数可以查找匹配项的索引。

def indexWhere(p: (A) ⇒ Boolean, from: Int): Int
> Finds index of the first element satisfying some predicate after or 
> at some start index.

http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Vector

我编写了这个函数来查找发生这种匹配的所有索引。

  def getAllIndexesWhere[A,B](as: List[A])(f: (B => Boolean))(g: A => B): Vector[B] = {
    def go(y: List[A], acc: List[Option[B]]): Vector[B] = as match {
      case x :: xs => val result = if (f(g(x))) Some(g(x)) else None
                      go(xs, acc :+ result)
      case Nil => acc.flatten.toVector
    }
    go(as, Nil)
  }

但是,是否已经有集合的内置功能?

【问题讨论】:

    标签: scala


    【解决方案1】:

    zipWithIndexfiltermap 是内置函数,可以组合起来获取某个谓词的所有索引。

    获取列表中偶数值的索引。

    scala> List(1,2,3,4,5,6,7,8,9,10).zipWithIndex.filter(_._1 % 2 == 0).map(_._2)
    res0: List[Int] = List(1, 3, 5, 7, 9)
    

    您也可以将collect 用作@0__ 注释。

    scala> List(1,2,3,4,5,6,7,8,9,10).zipWithIndex.collect{ case(a,b) if a % 2 == 0 => b}
    res1: List[Int] = List(1, 3, 5, 7, 9)
    

    【讨论】:

    • 你可以使用collect:collect { case (elem, idx) if pred(elem) => idx }
    • 非常好,布赖恩,谢谢。你能举个例子吗,@0__,collect
    • (1 to 10).zipWithIndex.collect { case (elem, idx) if elem % 2 == 0 => idx }
    • 使用索引压缩和重新映射是否会带来额外开销?我想vector必须已经有一个索引,这是zip允许您访问的内容,还是它构建了一个新集合?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-15
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 2012-01-28
    • 1970-01-01
    相关资源
    最近更新 更多