Last active
August 29, 2015 13:57
-
-
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.
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
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