Scala: List data structure

Objective – Generalize tail to the function drop, which removes the first n elements from a list.

 

 

 

object patternmatcing extends App {

sealed trait List[+A] // deifine trait list with sealed i.e all functions ust be declared here
case object Nil extends List[Nothing] // case object
case class Cons[+A](head: A, tail: List[A]) extends List[A] // case objectfor pattern match
object List { // create object list
def sum(ints: List[Int]): Int = ints match {
case Nil => 0
case Cons(x,xs) => x + sum(xs)
}

def tail(as:List[Int]):List[Int]= as match // function to remove first element
{
case Nil=> List(0)
case Cons(h,t) => t
}

def changehead(xs:List[Int]):List[Int]= xs match // function for replace head
{
case Cons(h,t)=>Cons(4,t)
}
def drop[A](l: List[A], n: Int): List[A]= (l,n) match
{
case (Cons(h,t),n)=> if (n>1)(drop(t,n-1)) else t // recursive loop for removal of element
// case (Nil,_) => Nil

}
def apply[A](as: A*): List[A] = // apply function which automatically calls when we defime list as paramater
if (as.isEmpty) Nil
else Cons(as.head, apply(as.tail: _*))
}
//println(List.changehead(List(1,2,3)))
// calling tail function outside object List
println(List.drop(List(1,2,3,4,5), 2))
}

 

 

 

Result : Cons(3,Cons(4,Cons(5,Nil)))

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s