Q:

Write a Scala program to calculate the length of a given list

0

Write a Scala program to calculate the length of a given list.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

object Scala_List {     
  def length[A](nums:List[A]):Int = {
    nums.length
   }  
  def main(args: Array[String]): Unit = {
     val nums1 = List(1,2,3,4)
     println("Original List:")
     println(nums1)
     println("Length of the said list:")   
     println(length(nums1))
     val nums2 = List(1, List(2, 3, 4), List(List(List(5, 6, 7))), List(8, 9), List(10), 11)
     println("Original List:")
     println(nums2)
     println("Length of the said list:")   
     println(length(nums2))    
     val colors = List("Red", "Green", "Black", "Pink", "Orange", "White","Yellow")
     println("Original List:")
     println(colors)
     println("Length of the said list:")
     println(length(colors))
    }
} 

Sample Output:

Original List:
List(1, 2, 3, 4)
Length of the said list:
4
Original List:
List(1, List(2, 3, 4), List(List(List(5, 6, 7))), List(8, 9), List(10), 11)
Length of the said list:
6
Original List:
List(Red, Green, Black, Pink, Orange, White, Yellow)
Length of the said list:
7

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now