function parse_parens(code)
pos_open = [i for (i, c) in enumerate(code) if c == '[']
pos_close = [i for (i, c) in enumerate(code) if c == ']']
if length(pos_open) != length(pos_close)
error("parenthesis mismatch")
end
dict_parenspos = Dict(zip(pos_open, reverse(pos_close)))
return dict_parenspos
end
function brainfuck(code)
tape = zeros(Int, 30_000)
tape_ptr = 1
code_ptr = 1
dict_parenspos = parse_parens(code)
stack = []
while code_ptr < length(code)
c = code[code_ptr]
if c == '[' && tape[tape_ptr] == 0
code_ptr = dict_parenspos[tape_ptr]
elseif c == '[' && tape[tape_ptr] != 0
push!(stack, code_ptr)
elseif c == ']' && tape[tape_ptr] == 0
pop!(stack)
elseif c == ']' && tape[tape_ptr] != 0
code_ptr = pop!(stack) - 1
elseif c == '>'
if 30_000 <= tape_ptr
error("Segmentation fault")
end
tape_ptr += 1
elseif c == '<'
if tape_ptr <= 0
error("Segmentation fault")
end
tape_ptr -= 1
elseif c == '+'
tape[tape_ptr] = mod(tape[tape_ptr] + 1, 256)
elseif c == '-'
tape[tape_ptr] = mod(tape[tape_ptr] - 1, 256)
elseif c == '.'
print( Char(tape[tape_ptr]) )
end
code_ptr += 1
end
end
code = """
+++++++++[>++++++++>+++++++++++>+++++<<<-]>.>++.+++++++..+++.>-.
------------.<++++++++.--------.+++.------.--------.>+.
"""
brainfuck(code)
こんな感じでしょうか。