Created
September 11, 2011 04:07
-
-
Save BlakeWilliams/1209153 to your computer and use it in GitHub Desktop.
Brainfuck interpreter in clojure!
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
(ns brain.fuck | |
(:gen-class)) | |
(def ptr (atom 0)) ; Initialize the pointer to 0 | |
(def cells (atom (vec (repeat 30000 0)))) ; Plenty of room! | |
(defn start [place commands] | |
(loop [brackets 1] | |
(when-not (== brackets 0) | |
(swap! place inc) | |
(case (nth commands @place) | |
\] (recur (dec brackets)) | |
\[ (recur (inc brackets)) | |
(recur brackets))))) | |
(defn end [place commands] | |
(loop [brackets 1] | |
(when-not (== brackets 0) | |
(swap! place dec) | |
(case (nth commands @place) | |
\] (recur (inc brackets)) | |
\[ (recur (dec brackets)) | |
(recur brackets))))) | |
(defn exec-command [commands place] | |
(case (nth commands @place) | |
\> (swap! ptr inc) ; Apply inc to ptr | |
\< (swap! ptr dec) ; Apply dec to ptr | |
\+ (reset! cells (assoc @cells @ptr (inc (get @cells @ptr)))) ; assoc makes new array with inc | |
\- (reset! cells (assoc @cells @ptr (dec (get @cells @ptr)))) ; assoc makes new array with dec | |
\. (print (char (get @cells @ptr))) ; Get the cell, turn it into a char, and print | |
\, (reset! cells (assoc @cells @ptr (int (char (. System/in read))))) | |
\[ (if (== (get @cells @ptr) 0) | |
(start place commands)) | |
\] (if-not (== (get @cells @ptr) 0) | |
(end place commands)) | |
())) | |
(defn interpret [commands] | |
(loop [place (atom 0)] | |
(exec-command commands place) | |
(swap! place inc) | |
(if-not (= @place (count commands)) | |
(recur place)))) | |
(defn -main [& args] | |
(if (nth args 0) | |
(interpret (slurp (nth args 0))) | |
(println "Please specify a file")) | |
(flush)) |
I've never tried to run it in clojurescript, I'll check it out and see if I can find a solution.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When I run this through clojurescript it complains about recur inside the case statements, would this be something missing in clojurescript?