Skip to content

Instantly share code, notes, and snippets.

@condotti
Created October 9, 2011 08:27
Show Gist options
  • Save condotti/1273454 to your computer and use it in GitHub Desktop.
Save condotti/1273454 to your computer and use it in GitHub Desktop.
brainfuck interpreter in Clojure
(defn brainfuck [s]
(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 [c dp ip]
(if (< ip (count s))
(let [[c dp ip]
(condp = (nth s ip)
\< [c (dec dp) ip]
\> [c (inc dp) ip]
\+ [(assoc c dp (inc (c dp))) dp ip]
\- [(assoc c dp (dec (c dp))) dp ip]
\. (do (print (char (c dp))) [c dp ip])
\, [(assoc c dp (byte (. System/in read))) dp ip]
\[ (if (= (c dp) 0) [c dp (fmb "][" inc ip)] [c dp ip])
\] (if (= (c dp) 0) [c dp ip] [c dp (fmb "[]" dec (dec ip))])
[c dp ip])]
(recur c dp (inc ip)))))
(into (vector-of :byte) (repeat 30000 0)) 0 0)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment