How to implement 'takeUntil' of a list?

后端 未结 6 1088
傲寒
傲寒 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:19

    You could use following function,

    def takeUntil(list: List[Int]): List[Int] = list match {
      case x :: xs if (x != 7) => x :: takeUntil(xs)
      case x :: xs if (x == 7) => List(x)
      case Nil => Nil
    }
    
    val list = List(1,4,5,2,3,5,5,7,8,9,2,7,4)
    takeUntil(list) //List(1,4,5,2,3,5,5,7)
    

    Tail Recursive version

    def takeUntilRec(list: List[Int]): List[Int] = {
        @annotation.tailrec
        def trf(head: Int, tail: List[Int], res: List[Int]): List[Int] = head match {
          case x if (x != 7 && tail != Nil) => trf(tail.head, tail.tail, x :: res)
          case x                            => x :: res
        }
        trf(list.head, list.tail, Nil).reverse
      }
    

提交回复
热议问题