scala – List – take, drop, splitAt

The expression “xs take n” returns the first n elements of the list xs.

If n is greater than xs.length, the whole list xs is returned.

 

The operation “xs drop n” returns all elements of the list xs except the first n ones.

If n is greater than xs.length, the empty list is returned.

 

The splitAt operationsplitsthelistatagivenindex, returningapairof two lists.4 It is defined by the equality:
xs splitAt n equals (xs take n, xs drop n)

 

object List_TakeDropSplitAt extends App{

  val v1=List(1,2,3)
  println(v1.take(1))
  println(v1 take(10))

  println(v1.drop(1))

  println(v1.splitAt(1))

}

List(1)
List(1, 2, 3)
List(2, 3)
(List(1),List(2, 3))

Leave a comment