简体   繁体   中英

Splitting the list in to two parts in Scala

I have a List with n as 3 ls as List(a,b,c,d,e) My query is to code for the (3,List(a,b,c,d,e)) I want to split them in to two parts such as List(a,b,c),List(d,e). For this the scala program is like below. I don't understand val(pre,post). why it is used and what do we get from it? can someone please elaborate?

def splitRecursive[A](n: Int, ls: List[A]): (List[A], List[A]) = (n, ls) match {
    case (_, Nil)       => (Nil, Nil)
    case (0, list)      => (Nil, list)
    case (n, h :: tail) => {
      val (pre, post) = splitRecursive(n - 1, tail)
      (h :: pre, post)
    }
  }

Your splitRecursive function returns a pair of lists. To get the two lists out of the pair, you can either fetch them like this:

val result = splitRecursive(n - 1, tail)
val pre = result._1
val post = result._2

Or you can use destructuring to get them without first having to bind the pair to result . That is what the syntax in splitRecursive is doing.

val (pre, post) = splitRecursive(n - 1, tail)

It is simply a convenient way to get the elements out of a pair (or some other structure that can be destructured).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM