solutions5/bf.scala
changeset 338 a1dc57326356
parent 337 c0d9e6548b08
equal deleted inserted replaced
337:c0d9e6548b08 338:a1dc57326356
     1 // Part 1 about an Interpreter for the Brainf***++ language
     1 // Core Part about an Interpreter for 
     2 //========================================================
     2 // the Brainf***++ language
     3 
     3 //==============================================
     4 
     4 
     5 object CW10a {  
     5 object CW10a {  
       
     6 
       
     7 
       
     8 // representation of Bf memory 
       
     9 
       
    10 type Mem = Map[Int, Int]
       
    11 
       
    12 
       
    13 // (1) Write a function that takes a file name as argument and
       
    14 // and requests the corresponding file from disk. It Returns the
       
    15 // content of the file as a String. If the file does not exists,
       
    16 // the function should Return the empty string.
     6 
    17 
     7 import io.Source
    18 import io.Source
     8 import scala.util._
    19 import scala.util._
     9 
       
    10 
       
    11 type Mem = Map[Int, Int]
       
    12 
       
    13 
       
    14 // (1) Write a function that takes a file name as argument and
       
    15 // and requests the corresponding file from disk. It returns the
       
    16 // content of the file as a String. If the file does not exists,
       
    17 // the function should return the empty string.
       
    18 
    20 
    19 def load_bff(name: String) : String = 
    21 def load_bff(name: String) : String = 
    20   Try(Source.fromFile(name)("ISO-8859-1").mkString).getOrElse("")
    22   Try(Source.fromFile(name)("ISO-8859-1").mkString).getOrElse("")
    21 
    23 
    22 
    24 
    80 // If the pc points to a character inside the program, the pc, 
    82 // If the pc points to a character inside the program, the pc, 
    81 // memory pointer and memory need to be updated according to 
    83 // memory pointer and memory need to be updated according to 
    82 // rules of the brainf***++ language. Then, recursively, the compute 
    84 // rules of the brainf***++ language. Then, recursively, the compute 
    83 // function continues with the command at the new program
    85 // function continues with the command at the new program
    84 // counter. 
    86 // counter. 
       
    87 //
    85 // Implement the run function that calls compute with the program
    88 // Implement the run function that calls compute with the program
    86 // counter and memory counter set to 0.
    89 // counter and memory counter set to 0.
    87 
    90 
    88 def compute(prog: String, pc: Int, mp: Int, mem: Mem) : Mem = {
    91 def compute(prog: String, pc: Int, mp: Int, mem: Mem) : Mem = {
    89   if (0 <= pc && pc < prog.length) { 
    92   if (0 <= pc && pc < prog.length) {