Skip to content

Instantly share code, notes, and snippets.

@orodio
Last active August 29, 2015 14:11
Show Gist options
  • Save orodio/c6bb846d1537da08f4aa to your computer and use it in GitHub Desktop.
Save orodio/c6bb846d1537da08f4aa to your computer and use it in GitHub Desktop.
robot.clj
(def robot (atom {:x 0 :y 0 :direction :north}))
(def behaviour {:left {:north :west
:west :south
:south :east
:east :north}
:right {:north :east
:east :south
:south :west
:west :north}})
(defn- error [msg] (println msg) :error)
(defn- set-val [k v] (swap! robot assoc k v) :ok)
(defn- face [dir] (set-val :direction dir))
(defn- valid? [x] (and (>= x 0) (< x 5)))
(defn- move-on-axis [axis f]
(let [v (f (axis @robot))]
(if (valid? v)
(set-val axis v)
(error "Out of bounds"))))
(defn- get-direction [] (@robot :direction))
(defn- new-direction [dir] (get-direction (behaviour dir)))
(defn- turn [dir] (face (new-direction dir)))
(defn left [] (turn :left))
(defn right [] (turn :right))
(defn move []
(cond (facing? :north) (move-on-axis :y inc)
(facing? :east) (move-on-axis :x dec)
(facing? :south) (move-on-axis :y dec)
(facing? :west) (move-on-axis :x inc)
:else (error "No x/y position")))
(defn report [] (str (:x @robot) "," (:y @robot) "," (:direction @robot)))
(report) ;; "0,0,:north"
(left) ;; :ok
(move) ;; :ok
(right) ;; :ok
(move) ;; :ok
(move) ;; :ok
(move) ;; :ok
(move) ;; :ok
(move) ;; :error
(move) ;; :error
(report) ;; "1,4,:north"
(right) ;; :ok
(right) ;; :ok
(move) ;; :ok
(report) ;; "1,3,:south"
(right) ;; :ok
(move) ;; :ok
(move) ;; :ok
(move) ;; :ok
(move) ;; :error
(report) ;; "4,3,:west"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment