9

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:

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

The result is:

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

Is there any other solution?

Freewind
  • 193,756
  • 157
  • 432
  • 708
  • `7` should not be included, per the standard library's definition: `scala> List(1,4,5,2,3,5,5,7,8,9,2,7,4).takeWhile(_ != 7) res0: List[Int] = List(1, 4, 5, 2, 3, 5, 5)`. Hint - consider using `List#foldRight`. – Kevin Meredith Nov 09 '15 at 05:05

7 Answers7

18

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)
  }
}
Aivean
  • 10,692
  • 25
  • 39
6

Borrowing the takeWhile implementation from scala.collection.List and changing it a bit:

def takeUntil[A](l: List[A], p: A => Boolean): List[A] = {
    val b = new scala.collection.mutable.ListBuffer[A]
    var these = l
    while (!these.isEmpty && p(these.head)) {
      b += these.head
      these = these.tail
    }
    if(!these.isEmpty && !p(these.head)) b += these.head

    b.toList
  }
marios
  • 8,874
  • 3
  • 38
  • 62
  • But overall I feel what you have in your question is pretty much the shortest and less verbose way of doing that. – marios Nov 09 '15 at 06:06
  • 1
    I used this answer because I actually want `spanUntil` - and this saves an iteration over the list. – tilde Apr 05 '21 at 14:16
3

Here's a way to get there with foldLeft, and a tail recursive version to short circuit long lists.

There's also the tests I used while playing around with this.

import scala.annotation.tailrec
import org.scalatest.WordSpec
import org.scalatest.Matchers

object TakeUntilInclusiveSpec {
  implicit class TakeUntilInclusiveFoldLeft[T](val list: List[T]) extends AnyVal {
    def takeUntilInclusive(p: T => Boolean): List[T] =
      list.foldLeft( (false, List[T]()) )({
        case ((false, acc), x)      => (p(x), x :: acc)
        case (res @ (true, acc), _) => res
      })._2.reverse
  }
  implicit class TakeUntilInclusiveTailRec[T](val list: List[T]) extends AnyVal {
    def takeUntilInclusive(p: T => Boolean): List[T] = {
      @tailrec
      def loop(acc: List[T], subList: List[T]): List[T] = subList match {
        case Nil => acc.reverse
        case x :: xs if p(x) => (x :: acc).reverse
        case x :: xs => loop(x :: acc, xs)
      }
      loop(List[T](), list)
    }
  }
}

class TakeUntilInclusiveSpec extends WordSpec with Matchers {
  //import TakeUntilInclusiveSpec.TakeUntilInclusiveFoldLeft
  import TakeUntilInclusiveSpec.TakeUntilInclusiveTailRec

  val `return` = afterWord("return")
  object lists {
    val one = List(1)
    val oneToTen = List(1, 2, 3, 4, 5, 7, 8, 9, 10)
    val boat = List("boat")
    val rowYourBoat = List("row", "your", "boat")
  }

  "TakeUntilInclusive" when afterWord("given") {
    "an empty list" should `return` {
      "an empty list" in {
        List[Int]().takeUntilInclusive(_ == 7) shouldBe Nil
        List[String]().takeUntilInclusive(_ == "") shouldBe Nil
      }
    }

    "a list without the matching element" should `return` {
      "an identical list" in {
        lists.one.takeUntilInclusive(_ == 20) shouldBe lists.one
        lists.oneToTen.takeUntilInclusive(_ == 20) shouldBe lists.oneToTen
        lists.boat.takeUntilInclusive(_.startsWith("a")) shouldBe lists.boat
        lists.rowYourBoat.takeUntilInclusive(_.startsWith("a")) shouldBe lists.rowYourBoat
      }
    }

    "a list containing one instance of the matching element in the last index" should `return`
    {
      "an identical list" in {
        lists.one.takeUntilInclusive(_ == 1) shouldBe lists.one
        lists.oneToTen.takeUntilInclusive(_ == 10) shouldBe lists.oneToTen
        lists.boat.takeUntilInclusive(_ == "boat") shouldBe lists.boat
        lists.rowYourBoat.takeUntilInclusive(_ == "boat") shouldBe lists.rowYourBoat
      }
    }

    "a list containing one instance of the matching element" should `return` {
      "the elements of the original list, up to and including the match" in {
        lists.one.takeUntilInclusive(_ == 1) shouldBe List(1)
        lists.oneToTen.takeUntilInclusive(_ == 5) shouldBe List(1,2,3,4,5)
        lists.boat.takeUntilInclusive(_ == "boat") shouldBe List("boat")
        lists.rowYourBoat.takeUntilInclusive(_ == "your") shouldBe List("row", "your")
      }
    }

    "a list containing multiple instances of the matching element" should `return` {
      "the elements of the original list, up to and including only the first match" in {
        lists.oneToTen.takeUntilInclusive(_ % 3 == 0) shouldBe List(1,2,3)
        lists.rowYourBoat.takeUntilInclusive(_.length == 4) shouldBe List("row", "your")
      }
    }
  }
}
Morgen
  • 1,010
  • 1
  • 11
  • 15
  • The order is changed :( – Freewind Nov 09 '15 at 04:57
  • Never mind, got my takeWhile and dropWhile switched. – Morgen Nov 09 '15 at 05:02
  • If the list doesn't contain a `7`, this will add one - which may or may not be what the OP wants, but seems a bit dubious to me (especially since it *doesn't* do that for the empty list). – Shadowlands Nov 09 '15 at 05:15
  • Yeah, I should have waited until after I got the kids to bed before posting. I should know better than to post while distracted by now. – Morgen Nov 09 '15 at 05:18
  • @Shadowlands Better now. Access to a repl makes it much easier to get to a decent solution. – Morgen Nov 09 '15 at 05:46
  • 1
    FYI, appending elements to `List` using `:+` is extremely inefficient. Currently your solution is O(N^2). Replace accumulator with `ListBuffer`, or, alternatively, use `::` (prepend) and `reverse` result in the end. – Aivean Nov 09 '15 at 06:51
  • @Aivean Yeah, this isn't an efficient solution, just another example of how it could be done. Fold isn't a good choice because it won't short circuit, so I'd probably never use this in production code. – Morgen Nov 09 '15 at 07:16
  • 1
    @Aivean This was supposed to be just a quick demo version, but it kept bugging me. So here's a O(n) foldLeft solution, and the O(n) tail recursive version I'd actually use if I had to do something like this in production code. – Morgen Nov 11 '15 at 00:33
2

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
  }
Johny T Koshy
  • 3,857
  • 2
  • 23
  • 40
  • 2
    This function is not tail-recursive, so it may fail with StackOverflow for long lists. Just FYI. – Aivean Nov 09 '15 at 06:35
2

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)
Nyavro
  • 8,806
  • 2
  • 26
  • 33
0

Some ways by use built-in functions:


val list = List(1, 4, 5, 2, 3, 5, 5, 7, 8, 9, 2, 7, 4)
//> list  : List[Int] = List(1, 4, 5, 2, 3, 5, 5, 7, 8, 9, 2, 7, 4)
//Using takeWhile with dropWhile
list.takeWhile(_ != 7) ++ list.dropWhile(_ != 7).take(1)
//> res0: List[Int] = List(1, 4, 5, 2, 3, 5, 5, 7)
//Using take with segmentLength
list.take(list.segmentLength(_ != 7, 0) + 1)
//> res1: List[Int] = List(1, 4, 5, 2, 3, 5, 5, 7) //Using take with indexOf list.take(list.indexOf(7) + 1) //> res2: List[Int] = List(1, 4, 5, 2, 3, 5, 5, 7)
mohit
  • 4,968
  • 1
  • 22
  • 39
0

Many of the solutions here are not very efficient, because they explore the whole list, rather than stopping early. Here is a short solution using the in-built functions:

def takeUntil[T](c: Iterable[T], f: T => Boolean): Iterable[T] = {
   val index = c.indexWhere(f)
   if (index == -1) c else c.take(index + 1)
}
Rok Kralj
  • 46,826
  • 10
  • 71
  • 80