如何实现列表的"takeUntil"? [英] How to implement 'takeUntil' of a list?

查看:88
本文介绍了如何实现列表的"takeUntil"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想查找所有与前一个7相等的项目:

I want to find all items before and equal the first 7:

val list = List(1,4,5,2,3,5,5,7,8,9,2,7,4)

我的解决方法是:

list.takeWhile(_ != 7) ::: List(7)

结果是:

List(1, 4, 5, 2, 3, 5, 5, 7)

还有其他解决方法吗?

推荐答案

不耐烦的一线:

List(1, 2, 3, 7, 8, 9, 2, 7, 4).span(_ != 7) match {case (h, t) => h ::: t.take(1)}


它将任何谓词作为参数.使用span来完成主要工作:

It takes any predicate as argument. Uses span to do the main job:

  implicit class TakeUntilListWrapper[T](list: List[T]) {
    def takeUntil(predicate: T => Boolean):List[T] = {
      list.span(predicate) match {
        case (head, tail) => head ::: tail.take(1)
      }
    }
  }

  println(List(1,2,3,4,5,6,7,8,9).takeUntil(_ != 7))
  //List(1, 2, 3, 4, 5, 6, 7)

  println(List(1,2,3,4,5,6,7,8,7,9).takeUntil(_ != 7))
  //List(1, 2, 3, 4, 5, 6, 7)

  println(List(1,2,3,4,5,6,7,7,7,8,9).takeUntil(_ != 7))
  //List(1, 2, 3, 4, 5, 6, 7)

  println(List(1,2,3,4,5,6,8,9).takeUntil(_ != 7))
  //List(1, 2, 3, 4, 5, 6, 8, 9)


只是为了说明替代方法,它没有比以前的解决方案更有效.

Just to illustrate alternative approach, it's not any more efficient than previous solution.

implicit class TakeUntilListWrapper[T](list: List[T]) {
  def takeUntil(predicate: T => Boolean): List[T] = {
    def rec(tail:List[T], accum:List[T]):List[T] = tail match {
      case Nil => accum.reverse
      case h :: t => rec(if (predicate(h)) t else Nil, h :: accum)
    }
    rec(list, Nil)
  }
}

这篇关于如何实现列表的"takeUntil"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆