Brainfuck Interpreter in 40 lines of Scala

Ever heard of the esoteric programming language Brainfuck? It only has eight commands, very minimalistic, very unreadable but Turing complete. I spent some time to develop an interpreter for this language in Scala. Here it is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import Array._
 
object Brainfuck 
{
    def run( bf : Array[Char] ) = {
	var memory : Array[Integer] = Array.fill[Integer](30000)(0)
	var memptr : Integer = 0
	var prgptr : Integer = 0
 
        def jump( dir : Int ) = {
	    var loop = 1
	    while( loop > 0 ) {
	        prgptr += dir
	        loop += (bf( prgptr ) match {
	    	    case '[' => dir
	    	    case ']' => -dir
	    	    case _ => 0
	        })
	    }
        }
 
        while( prgptr < bf.size ) {
	    bf(prgptr) match {
	        case '>' => memptr += 1
	        case '<' => memptr -= 1
	        case '+' => memory(memptr) += 1
	        case '-' => memory(memptr) -= 1
	        case '.' => print( memory(memptr).toChar )
                case ',' => memory(memptr) = readInt()
	        case '[' => if( memory( memptr ) == 0 ) jump( 1 ) 
	        case ']' => if( memory( memptr) != 0 ) jump( -1 ) 
	    }
	    prgptr += 1
        }
    }
 
    def main( args: Array[String] ) = {
        run( "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.".toCharArray() )
    }
}

As you might guess, the example program will print “Hello World!”.

Fork me on GitHub