Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
object HelloWorld {
sealed trait List[+A]
case object Nil extends List[Nothing]
case class Cons[+A](head: A, tail: List[A]) extends List[A]
object List {
def sum(ints: List[Int]): Int = ints match {
case Nil => 0
case Cons(x,xs) => x + sum(xs)
}
def product(ds: List[Double]): Double = ds match {
case Nil => 1.0
case Cons(0.0, _) => 0.0
case Cons(x,xs) => x * product(xs)
}
def apply[A](as: A*): List[A] =
if (as.isEmpty) Nil
else Cons(as.head, apply(as.tail: _*))
def tail[A](ls: List[A]): List[A] = ls match {
case Nil => Nil
case Cons(_,t) => t
}
def setHead[A](ls: List[A], nHead: A): List[A] = ls match {
case Nil => Nil
case Cons(_,t) => Cons(nHead,t)
}
def drop[A](l: List[A], n: Int): List[A] = l match {
case Cons(h,t) => if (n>0) drop(t,n-1) else l
}
def dropWhile[A](l: List[A], f: A => Boolean): List[A] = l match {
case Nil => Nil
case Cons(h,t) => if (!f(h)) l else dropWhile(t,f)
}
def init[A](l: List[A]): List[A] = l match {
case Nil => Nil
case (_,Nil) => Nil
case Cons(h,t) => Cons(h,init(t))
}
}
def main(args: Array[String]) {
val a = List(22,2,3,4,5) match { case Cons(_,t) => t }
val b= List.dropWhile(List(22,11,22,44,55), (x:Int) => x==22 )
val c= List.drop(List(22,11,22,44,55), 2 )
println(c)
}
}
Advertisements
We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.
AcceptLearn more