Scala : List data structure element removal

Objective –


Implement the function tail for removing the first element of a List.

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 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.tail(List(1,2,3))) // calling tail function outside object List


Output – Cons(2,Cons(3,Nil))




Leave a Reply

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

You are commenting using your 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