How to implement 'takeUntil' of a list?

后端 未结 6 1089
傲寒
傲寒 2021-01-05 01:52

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)

My solution is:



        
6条回答
  •  一整个雨季
    2021-01-05 02:33

    One-liner for impatient:

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


    More generic version:

    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)
    


    Tail-recursive version.

    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)
      }
    }
    

提交回复
热议问题