Created
April 15, 2011 03:49
-
-
Save yatt/921109 to your computer and use it in GitHub Desktop.
brainf*ck interpreter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sys import stdin, stdout | |
# state | |
class Int(object): | |
def __init__(self, v=0): self.val = v | |
def set(self, v): self.val = v; return self.val | |
def inc(self): self.val += 1; return self.val | |
def dec(self): self.val -= 1; return self.val | |
mem = [Int() for i in range(255)] | |
stk = [] | |
ptr = Int() | |
idx = Int(-1) | |
# procedure | |
proc = { | |
'+': lambda: mem[ptr.val].inc(), | |
'-': lambda: mem[ptr.val].dec(), | |
'>': lambda: ptr.inc(), | |
'<': lambda: ptr.dec(), | |
',': lambda: mem[ptr.val].set(ord(stdin.read(1))), | |
'.': lambda: stdout.write(chr(mem[ptr.val].val)), | |
'[': lambda: stk.append(idx.val), | |
']': lambda: mem[ptr.val].val != 0 and idx.set(stk[-1]) or stk.pop(), | |
} | |
# interpret | |
bfprog = stdin.read() | |
while len(bfprog) != idx.inc(): | |
proc.get(bfprog[idx.val], lambda:1)() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment