progs/lecture3.scala
changeset 445 160cbb09027f
parent 415 368556c8df56
child 446 30b8f14b2655
equal deleted inserted replaced
444:e6df3c7ff132 445:160cbb09027f
     1 // Scala Lecture 3
     1 // Scala Lecture 3
     2 //=================
     2 //=================
     3 
     3 
       
     4 // - maps (behind for-comprehensions)
       
     5 // - Pattern-Matching
       
     6 
       
     7 abstract class Rexp
       
     8 case object ZERO extends Rexp                      // matches nothing
       
     9 case object ONE extends Rexp                       // matches the empty string
       
    10 case class CHAR(c: Char) extends Rexp              // matches a character c
       
    11 case class ALT(r1: Rexp, r2: Rexp) extends Rexp    // alternative
       
    12 case class SEQ(r1: Rexp, r2: Rexp) extends Rexp    // sequence
       
    13 case class STAR(r: Rexp) extends Rexp              // star
       
    14 
       
    15 def depth(r: Rexp) : Int = r match {
       
    16   case ZERO => 1
       
    17   case ONE => 1
       
    18   case CHAR(_) => 1
       
    19   case ALT(r1, r2) => 1 + List(depth(r1), depth(r2)).max
       
    20   case SEQ(r1, r2) => 1 + List(depth(r1), depth(r2)).max
       
    21   case STAR(r1) => 1 + depth(r1)
       
    22 }
       
    23 
       
    24 
       
    25 // - String-Interpolations
       
    26 
       
    27 // String Interpolations
       
    28 //=======================
       
    29 
       
    30 def cube(n: Int) : Int = n * n * n
       
    31 
       
    32 val n = 3
       
    33 println("The cube of " + n + " is " + cube(n) + ".")
       
    34 
       
    35 println(s"The cube of $n is ${cube(n)}.")
       
    36 
       
    37 // or even
       
    38 
       
    39 println(s"The cube of $n is ${n * n * n}.")
       
    40 
       
    41 // helpful for debugging purposes
       
    42 //
       
    43 //     "The most effective debugging tool is still careful 
       
    44 //          thought, coupled with judiciously placed print 
       
    45 //                                             statements."
       
    46 //       — Brian W. Kernighan, in Unix for Beginners (1979)
       
    47 
       
    48 
       
    49 def gcd_db(a: Int, b: Int) : Int = {
       
    50   println(s"Function called with $a and $b.")
       
    51   if (b == 0) a else gcd_db(b, a % b)
       
    52 }
       
    53 
       
    54 gcd_db(48, 18)
     4 
    55 
     5 
    56 
     6 // naive quicksort with "On" function
    57 // naive quicksort with "On" function
     7 
    58 
     8 def sortOn(f: Int => Int, xs: List[Int]) : List[Int] = {
    59 def sortOn(f: Int => Int, xs: List[Int]) : List[Int] = {