Skip to content

Instantly share code, notes, and snippets.

@z-------------
Last active March 26, 2023 08:15
Show Gist options
  • Save z-------------/88fb09ea0587cc3555942e7ea5f400af to your computer and use it in GitHub Desktop.
Save z-------------/88fb09ea0587cc3555942e7ea5f400af to your computer and use it in GitHub Desktop.
func findMatching(s: string; first, last: Natural; a, b: static char; d: static int): int {.raises: [ValueError].} =
var i = first.int
var level = 0
while true:
if s[i] == a:
inc level
elif s[i] == b:
dec level
if level == 0:
return i
if i == last:
raise newException(ValueError, "invalid program")
else:
i += d
proc interpret*(program: string) {.raises: [ValueError, IOError].} =
var data: array[30_000, byte]
var dp = 0
var pc = 0
while pc < program.len:
case program[pc]
of '>': inc dp
of '<': dec dp
of '+': inc data[dp]
of '-': dec data[dp]
of '.': stdout.write data[dp].char
of ',': data[dp] = stdin.readChar.byte
of '[':
if data[dp] == 0:
pc = findMatching(program, pc, program.high, '[', ']', d = 1)
of ']':
if data[dp] != 0:
pc = findMatching(program, pc, 0, ']', '[', d = -1)
else: discard
inc pc
when isMainModule:
interpret "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment