Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
(defn pair-brackets [indexed]
(fn [pairs cur]
(condp = (cur 1)
\[ (merge-with conj pairs {:pend (cur 0)})
\] (merge pairs
{(first (pairs :pend)) (cur 0)
(cur 0) (first (pairs :pend))
:pend (pop (pairs :pend))})
{:pend ()} indexed))
(defn brainfuck [insns]
[valid (set "[]<>-+.,")
program (vec (keep #(valid %) insns))
jumps (pair-brackets
(map vector (range) program))]
[pc 0 ; program counter
bp 0 ; byte pointer
tape {}]
(if (< pc (count program))
(let [insn (program pc)
cur (tape bp 0)]
(if (= \. insn)
(print (char cur)))
(and (= \[ insn) (= 0 cur)) jumps
(and (= \] insn) (not= 0 cur)) jumps
:else inc) pc)
(({\< dec \> inc} insn identity) bp)
(#{\- \+} insn)
(merge tape {bp (({\- dec \+ inc} insn) cur)})
(= \, insn)
(merge tape {bp (. System/in read)})
:else tape)))))))
(-> *command-line-args*
last slurp brainfuck)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment