Skip to content

Instantly share code, notes, and snippets.

@threeifbywhiskey
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save threeifbywhiskey/9625243 to your computer and use it in GitHub Desktop.
Save threeifbywhiskey/9625243 to your computer and use it in GitHub Desktop.
A brainfuck interpreter written using mostly lambdas, helped along by the Church gem.
require 'church'
include Church
brainfuck = -> prog {
tape = []
sz = SIZE[prog]
pc = bp = i = 0
jumps, stack = {}, []
(jumper = -> {
prog[i] == '[' ? (stack << i) : 0
prog[i] == ']' ? (jumps[stack[-1]] = i; stack = stack[0..-2]) : 0
(i += 1) == sz ? 0 : jumper[]
})[]
jumps = jumps == {} ? {} : MERGE[jumps, INVERT[jumps]]
(brainfuck_p = -> {
prog[pc] ==
'+' ? (tape[bp] ||= 0; tape[bp] += 1) : prog[pc] ==
'-' ? (tape[bp] ||= 0; tape[bp] -= 1) : prog[pc] ==
'>' ? (bp += 1) : prog[pc] ==
'<' ? (bp -= 1) : prog[pc] ==
'[' ? (pc = (tape[bp] || 0) == 0 ? jumps[pc] : pc) : prog[pc] ==
']' ? (pc = (tape[bp] || 0) != 0 ? jumps[pc] : pc) : prog[pc] ==
'.' ? ($> << ('' << tape[bp])) : 0
(pc += 1) == sz ? prog : brainfuck_p[]
})[]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment