Created
October 9, 2011 08:32
-
-
Save condotti/1273458 to your computer and use it in GitHub Desktop.
brainfuck interpreter in Clojure, transient vector version
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
(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