scala/recs.scala
changeset 193 317a2532c567
child 194 fc2a5e9fbb97
equal deleted inserted replaced
192:3c1107984b41 193:317a2532c567
       
     1 package object recs {
       
     2 
       
     3 
       
     4 //Recursive Functions
       
     5 abstract class Rec {
       
     6   def eval(ns: List[Int]) : Int
       
     7 }
       
     8 case object Z extends Rec {
       
     9   override def eval(ns: List[Int]) = ns match {
       
    10     case n::Nil => 0
       
    11     case _ => throw new IllegalArgumentException("Z: args")
       
    12   }
       
    13 } 
       
    14 case object S extends Rec {
       
    15   override def eval(ns: List[Int]) = ns match {
       
    16     case n::Nil => n + 1
       
    17     case _ => throw new IllegalArgumentException("S: args")
       
    18   }
       
    19 } 
       
    20 case class Id(n: Int, m: Int) extends Rec {
       
    21   override def eval(ns: List[Int]) = 
       
    22     if (ns.length == n && m < n) ns(m)
       
    23     else throw new IllegalArgumentException("Id: args")
       
    24 }
       
    25 case class Cn(n: Int, f: Rec, gs: List[Rec]) extends Rec {
       
    26   override def eval(ns: List[Int]) = 
       
    27     if (ns.length == n) f.eval(gs.map(_.eval(ns)))
       
    28     else throw new IllegalArgumentException("Cn: args")
       
    29 }
       
    30 case class Pr(n: Int, f: Rec, g: Rec) extends Rec {
       
    31   override def eval(ns: List[Int]) = 
       
    32     if (ns.length == n - 1) {
       
    33       if (ns.last == 0) f.eval(ns.init)
       
    34       else {
       
    35         val r = Pr(n, f, g).eval(ns.init ::: List(ns.last - 1))
       
    36         g.eval(ns.init ::: List(ns.last - 1, r))
       
    37       }
       
    38     }
       
    39     else throw new IllegalArgumentException("Cn: args")
       
    40 }
       
    41 case class Mn(n: Int, f: Rec) extends Rec {
       
    42   override def eval(ns: List[Int]) = 0
       
    43     
       
    44 }
       
    45 
       
    46 }