This is a small interpreter for BF I wrote about a month ago. Nothing new, but I thought I might share it anyway.

A small usage example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
package de.niklaskorz.brainfuck

class Interpreter {
  var offset = 0
  var data = new Array[Char](30000)
  var loopStart = new scala.collection.mutable.Stack[Int]

  def eval(source: String) {
    var i = 0
    while (i < source.length) { source(i) match {
      case '>' => offset += 1
      case '<' => offset -= 1
      case '+' => data(offset) = (data(offset) + 1).toChar
      case '-' => data(offset) = (data(offset) - 1).toChar
      case '.' => print(data(offset))
      case ',' => data(offset) = Console.in.read.toChar
      case '[' => loopStart.push(i)
      case ']' => if (data(offset) != 0) i = loopStart.head else loopStart.pop
      case _ =>
    }; i += 1 }
  }
}
Listing 1. brainfuck.scala
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
package de.niklaskorz.brainfuck

import scala.io.Source

object App {
  def main(args: Array[String]) {
    var interpreter = new Interpreter
    var source = Source.fromFile(args(0)).mkString
    interpreter.eval(source)
  }
}
Listing 2. main.scala

I’ve tested it with the hello world program from Wikipedia and the “99 Bottles of Beer” program which I found on this page.

Hello world:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
+++++ +++++             initialize counter (cell #0) to 10
[                       use loop to set the next four cells to 70/100/30/10
    > +++++ ++              add  7 to cell #1
    > +++++ +++++           add 10 to cell #2 
    > +++                   add  3 to cell #3
    > +                     add  1 to cell #4
    <<<< -                  decrement counter (cell #0)
]                   
> ++ .                  print 'H'
> + .                   print 'e'
+++++ ++ .              print 'l'
.                       print 'l'
+++ .                   print 'o'
> ++ .                  print ' '
<< +++++ +++++ +++++ .  print 'W'
> .                     print 'o'
+++ .                   print 'r'
----- - .               print 'l'
----- --- .             print 'd'
> + .                   print '!'
> .                     print '\n'
Listing 3. helloworld.bf

Edit (19th January 2013): As mentioned in the comments, the way this interpreter handles loops is more like a do-while instead of a while loop.