cjm cjm - 4 months ago 11
Brainfuck Question

Better way to implement interpreter in Python

I am attempting to implement an interpreter for brainfuck and as of now, I am just using a series of if/elif statements.

if(i == ">"):
...
elif(i == "<"):
...
elif(i == "+"):
...
elif(i == "-"):
...


However, this seems very clunky and un-pythonic to me. Is there a better (cleaner/faster/more aesthetically pleasing) way to implement this?

Answer

I have a quick implementation of a Brainfuck interpreter for Python in a GitHub repo. In a nutshell, though, you could keep a dictionary, where the keys are the Brainfuck characters and the values are function (or method) objects, and then dispatch on that. Something like this:

instructions = {
  '+': increment,
  '-': decrement,
  # Other functions
}

def run(tape):
  ch = next_token(tape)
  if ch in instructions:
    instructions[ch]()

(Not an actual implementation, just a quick illustration.)