Skip to content

Instantly share code, notes, and snippets.

@jmgimeno
Created June 14, 2012 07:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmgimeno/2928678 to your computer and use it in GitHub Desktop.
Save jmgimeno/2928678 to your computer and use it in GitHub Desktop.
Brainf*** compiler (Alan Dipert)
(defn bfc
[program]
(let [allowed #{\+ \- \< \> \[ \] \.}
src (->> program (filter allowed)
(interpose \space) (apply str))
fns (zipmap '(- + < > . ?) (repeatedly gensym))]
(letfn [(bfc* [s]
(if (vector? s)
`(while (not (~(fns '?))) ~@(map bfc* s))
`(~(fns s))))]
`(let [tape# (int-array 60000 0)
pointer# (atom 0)
~(fns '-) #(aset tape# @pointer# (dec (aget tape# @pointer#)))
~(fns '+) #(aset tape# @pointer# (inc (aget tape# @pointer#)))
~(fns '<) #(swap! pointer# dec)
~(fns '>) #(swap! pointer# inc)
~(fns '.) #(print (char (aget tape# @pointer#)))
~(fns '?) #(zero? (aget tape# @pointer#))]
~@(map bfc* (read-string (str "(" src ")"))) nil))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment