scala/lib.scala
changeset 221 18905d086cbb
parent 193 317a2532c567
equal deleted inserted replaced
220:262fc2c6371b 221:18905d086cbb
     1 package object lib {
     1 package object lib {
     2 
     2 
     3 //some list functions
     3 //some list functions
     4 def tl[A](xs: List[A]) : List[A] = xs match {
     4 //slow version
     5   case Nil => Nil
     5 //def tl[A](xs: List[A]) : List[A] = xs match {
     6   case x::xs => xs
     6 //  case Nil => Nil
     7 }
     7 //  case x::xs => xs
       
     8 //}
       
     9 
       
    10 def tl[A](xs: List[A]) : List[A] = 
       
    11   try { xs.tail } catch { case _:UnsupportedOperationException => Nil }
     8 
    12 
     9 def hd[A](xs: List[A]) : A = xs.head
    13 def hd[A](xs: List[A]) : A = xs.head
    10 
    14 
       
    15 //slow version
       
    16 //def nth_of[A](xs: List[A], n: Int) = 
       
    17 //  if (n <= xs.length) Some(xs(n)) else None 
       
    18 
    11 def nth_of[A](xs: List[A], n: Int) = 
    19 def nth_of[A](xs: List[A], n: Int) = 
    12   if (n <= xs.length) Some(xs(n)) else None 
    20   try { Some(xs(n)) } catch { case _:IndexOutOfBoundsException => None }
    13 
    21 
    14 //some map functions
    22 //some map functions
    15 def dget(m: Map[Int, Int], n: Int) = m.getOrElse(n, 0)
    23 def dget(m: Map[Int, Int], n: Int) = m.getOrElse(n, 0)
    16 
    24 
    17 //some string functions
    25 //some string functions