What is the meaning of case in match pattern in scala? -


  val list1 = list(1, 1, 2, 3, 5,7,8,4)   def lastrecursive[a](ls :list[a]):a = ls match{   case p :: nil => p    // meaning of nil   case _ :: tail => lastrecursive(tail)   case _ => throw new nosuchelementexception    } 

for code above in recursive format. can explain why giving :: , case h , case tail , case _. while working on list match pattern.

   , reversing list     def reverserecursive[a](ls: list[a]): list[a] = ls match {      case nil       => nil      case h :: tail => reverserecursive(tail) ::: list(h)           }   

how ::: list(h) works?

the :: method used construct , deconstruct list. a::b means head of list (a single element) , tail b (a list).

p::nil means case there element p , tail empty list (nil).

this case finds last actual element in list.

the second case similar: h::tail means element h , list tail. reverse tail , add list of h end (l1 ::: l2 prepends list l1 list l).


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -