• Clojure
  • 44 lines
  • Pasted by anonymous on March 6, 2014
(ns bf.core)

(defn update [map key & rest]
  ; purely for conveniance
  (apply update-in map [key] rest))

(defn extend-cells [cells current-cell]
  (if (= (count cells) current-cell)
    (conj cells 0N)

(defn find-bracket [code open-ch close-ch ip next]
  (loop [ip (next ip) opened 0]
    (condp = (nth code ip)
      open-ch (recur (next ip) (inc opened))
      close-ch (if (zero? opened) ip (recur (next ip) (dec opened)))
      (recur (next ip) opened))))

(defn bf-step [{:keys [program-code cells cc ip] :as s}]
  (condp = (get program-code ip)
    \<  (-> s (update :cc dec) (update :ip inc))
    \>  (let [cc (inc cc)]
          (assoc s :cc cc :cells (extend-cells cells cc) :ip (inc ip)))
    \+  (-> s (update-in [:cells cc] inc) (update :ip inc))
    \-  (-> s (update-in [:cells cc] dec) (update :ip inc))
    \.  (do
          (print (char (nth cells cc)))
          (update s :ip inc))
    \,  (let [ch (.read System/in)]
          (-> s (assoc-in [:cells cc] ch) (update :ip inc)))
    \[  (assoc s :ip (inc (if (zero? (nth cells cc))
                            (find-bracket program-code \[ \] ip inc)
    \]  (assoc s :ip (find-bracket program-code \] \[ ip dec))
    nil nil ;EOF
    (update s :ip inc)))

(defn bf-interpreter [program-code]
    (dorun (take-while (comp not nil?) (iterate bf-step {:program-code program-code :cells [0N] :cc 0 :ip 0}))))

(defn -main [& args]
  (if (nth args 0)
    (bf-interpreter (slurp (nth args 0)))
    (println "Please specify a brainfuck file as the first argument")))

Did you know? CLOSE

  • There are keyboard shortcuts!
    • When Creating A Paste
      • ALT+P Toggle Private
      • CTRL+Enter Create Paste
      • ALT+W Toggle word wrap
    • When Viewing A Paste
      • ALT+G Go to a line
      • ALT+CTRL+E Edit the paste
      • ALT+R Show the raw code
  • There are URL options!
    • When Creating A Paste
      • ?lang=Javascript to default to javascript
    • When Viewing A Paste
      • #L-N Jump to line number N