Best way to implement interpreter in Python

I'm trying to implement an interpreter for brainfuck, and for now, I'm just using a series of if / elif statements.

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

However, this seems very awkward and non-creepy to me. Is there a better (cleaner / faster / more aesthetic) way to implement this?

+4
source share
1 answer

I have a quick implementation of the Brainfuck interpreter for Python in the GitHub repository . In a nutshell, however, you can save a dictionary where the keys are Brainfuck characters and the values โ€‹โ€‹are objects of a function (or method) and then sent to that. Something like that:

 instructions = { '+': increment, '-': decrement, # Other functions } def run(tape): ch = next_token(tape) if ch in instructions: instructions[ch]() 

(Not a real implementation, just a brief illustration.)

+6
source

Source: https://habr.com/ru/post/1494548/


All Articles