Reputation: 417
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)
}
}
Upvotes: 0
Views: 104
Reputation: 28066
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).
Upvotes: 2