Skip to content

Instantly share code, notes, and snippets.

@condotti
Created October 9, 2011 08:32
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 condotti/1273458 to your computer and use it in GitHub Desktop.
Save condotti/1273458 to your computer and use it in GitHub Desktop.
brainfuck interpreter in Clojure, transient vector version
(defn brainfuck2 [s]
(let [c (transient (vec (repeat 30000 (byte 0))))]
(letfn [(fmb [[t p] f ip] ; find matching bracket
((fn [ip n]
(condp = (nth s ip)
t (if (= n 0) ip (recur (f ip) (dec n)))
p (recur (f ip) (inc n))
(recur (f ip) n)))
ip 0))]
((fn [dp ip]
(if (< ip (count s))
(let [[dp ip]
(condp = (nth s ip)
\< [(dec dp) ip]
\> [(inc dp) ip]
\+ (do (assoc! c dp (inc (c dp))) [dp ip])
\- (do (assoc! c dp (dec (c dp))) [dp ip])
\. (do (print (char (c dp))) [dp ip])
\, (do (assoc! c dp (byte (. System/in read))) [dp ip])
\[ (if (= (c dp) 0) [dp (fmb "][" inc ip)] [dp ip])
\] (if (= (c dp) 0) [dp ip] [dp (fmb "[]" dec (dec ip))])
[dp ip])]
(recur dp (inc ip)))))
0 0))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment