How to implement 'takeUntil' of a list?

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

    Possible way of doing this:

    def takeUntil[A](list:List[A])(predicate: A => Boolean):List[A] =
      if(list.isEmpty) Nil
      else if(predicate(list.head)) list.head::takeUntil(list.tail)(predicate)
      else List(list.head)
    

提交回复
热议问题