progs/bf/bfi.sc
changeset 738 084e2843f478
parent 737 14a348d050b3
child 742 b5b5583a3a08
equal deleted inserted replaced
737:14a348d050b3 738:084e2843f478
     1 // A simple Interpreter for BF*** Programs
     1 // A simple Interpreter for BF*** Programs
     2 //=========================================
     2 //=========================================
     3 //
     3 //
     4 // Call
     4 // Call with
     5 //
     5 //
     6 //  amm bfi.sc <<bf_program.bf>>
     6 //  amm bfi.sc <<bf_program.bf>>
       
     7 //
     7 
     8 
     8 
     9 
     9 import scala.util._
    10 import scala.util._
    10 
    11 
    11 // BF memory as a map
    12 // BF memory as a map
    15 def sread(mem: Mem, mp: Int) : Int = 
    16 def sread(mem: Mem, mp: Int) : Int = 
    16   mem.getOrElse(mp, 0)
    17   mem.getOrElse(mp, 0)
    17 
    18 
    18 def write(mem: Mem, mp: Int, v: Int) : Mem =
    19 def write(mem: Mem, mp: Int, v: Int) : Mem =
    19   mem.updated(mp, v)
    20   mem.updated(mp, v)
    20 
       
    21 
    21 
    22 // Right and Left Jumps in BF loops
    22 // Right and Left Jumps in BF loops
    23 def jumpRight(prog: String, pc: Int, level: Int) : Int = {
    23 def jumpRight(prog: String, pc: Int, level: Int) : Int = {
    24   if (prog.length <= pc) pc 
    24   if (prog.length <= pc) pc 
    25   else (prog(pc), level) match {
    25   else (prog(pc), level) match {
    71   for (i <- 0 until n) code
    71   for (i <- 0 until n) code
    72   val end = System.nanoTime()
    72   val end = System.nanoTime()
    73   (end - start)/(n * 1.0e9)
    73   (end - start)/(n * 1.0e9)
    74 }
    74 }
    75 
    75 
    76 // Testcases
    76 // Running Testcases
    77 //===========
    77 //===================
    78 
    78 
    79 @doc(" the argument should be a BF program ")
    79 @doc(" the argument should be a BF program ")
    80 @main
    80 @main
    81 def main(fname: String) = {
    81 def main(fname: String) = {
    82   val bf_str = os.read(os.pwd / fname)
    82   val bf_str = os.read(os.pwd / fname)