scala/abacus.scala
changeset 194 fc2a5e9fbb97
parent 193 317a2532c567
child 195 f06aa4e1c25b
equal deleted inserted replaced
193:317a2532c567 194:fc2a5e9fbb97
     1 package object abacus {
     1 package object abacus {
     2 
     2 
     3 import lib._
     3 import lib._
     4 
     4 
     5 // Abacus machines
     5 // Abacus instructions
     6 sealed abstract class AInst 
     6 sealed abstract class AInst 
     7 case class Inc(n: Int) extends AInst
     7 case class Inc(n: Int) extends AInst
     8 case class Dec(n: Int, l: Int) extends AInst
     8 case class Dec(n: Int, l: Int) extends AInst
     9 case class Goto(l: Int) extends AInst
     9 case class Goto(l: Int) extends AInst
    10 
    10 
    11 type AProg = List[AInst]
    11 type AProg = List[AInst]
    12 type Regs = Map[Int, Int]
    12 type Regs = Map[Int, Int]
    13 
    13 
       
    14 // Abacus configurations
    14 case class AConfig(s: Int, regs: Regs)  
    15 case class AConfig(s: Int, regs: Regs)  
    15 
    16 
       
    17 // Abacus machines
    16 case class Abacus(p: AProg) {
    18 case class Abacus(p: AProg) {
    17 
    19 
       
    20   //simple composition
    18   def ++ (that: Abacus) = Abacus(this.p ::: that.p)
    21   def ++ (that: Abacus) = Abacus(this.p ::: that.p)
    19 
    22 
    20   def shift(offset: Int, jump: Int) = Abacus(p.map(_ match {
    23   def shift(offset: Int, jump: Int) = Abacus(p.map(_ match {
    21     case Inc(n) => Inc(n)
    24     case Inc(n) => Inc(n)
    22     case Dec(n, l) => if (l == jump) Dec(n, l) else Dec(n, l + offset)
    25     case Dec(n, l) => if (l == jump) Dec(n, l) else Dec(n, l + offset)