Scala:List Data Structure

Objective :

implement the function setHead for replacing the first element
of a List with a different value.

Solution:-

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 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
}

 

 

Output:-

 

Cons(4,Cons(2,Cons(3,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