Scala Programming: Split a given list into two lists
Write a Scala program to split a given list into two lists.
Sample Solution:
Scala Code:
object Scala_List {
def split_list[A](nums: List[A], n: Int): (List[A], List[A]) = {
(nums.take(n), nums.drop(n))
}
def main(args: Array[String]): Unit = {
val nums1 = List(1,2,3,4,5,6)
println("Original List:")
println("Split the said list into 2 lists:")
println(split_list(nums1, 2))
println(split_list(nums1, 3))
}
}
Sample Output:
Original List: Split the said list into 2 lists: (List(1, 2),List(3, 4, 5, 6)) (List(1, 2, 3),List(4, 5, 6))
Scala Code Editor :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Scala program to count the number of occurrences of each element in a given list.
Next: Write a Scala program to calculate the length of a given list.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics