Skip to content

Instantly share code, notes, and snippets.

@schmalz
Created February 3, 2023 10:52
Show Gist options
  • Save schmalz/2e4145aa03a7373a877eeb50b55ee685 to your computer and use it in GitHub Desktop.
Save schmalz/2e4145aa03a7373a877eeb50b55ee685 to your computer and use it in GitHub Desktop.
Clojure implementation of the Robbie Robot Keyboard Exercise from Common Lisp: A Gentle Introduction to Symbolic Computing
(ns robbie.core)
(def rooms
"Robbie's world."
{:living-room {:north :front-stairs
:south :dining-room
:east :kitchen}
:upstairs-bedroom {:west :library
:south :front-stairs}
:dining-room {:north :living-room
:east :pantry
:west :downstairs-bedroom}
:kitchen {:west :living-room
:south :pantry}
:pantry {:north :kitchen
:west :dining-room}
:downstairs-bedroom {:north :back-stairs
:east :dining-room}
:back-stairs {:south :downstairs-bedroom
:north :library}
:front-stairs {:north :upstairs-bedroom
:south :living-room}
:library {:east :upstairs-bedroom
:south :back-stairs}})
(def ^:private loc
"Robbie's current location."
(atom :pantry))
(defn- set-robbie-location
"Set Robbie's location to ROOM."
[room]
(reset! loc room))
(defn choices
"Given ROOM, what are the choices for movement?"
[room]
(rooms room))
(defn look
"The room that lies in DIRECTION from ROOM (nil if no room lies in that
direction)."
[direction room]
((choices room) direction))
(defn how-many-choices
"Given Robbie's current location, how many choices for movement does he
have?"
[]
(count (choices @loc)))
(defn upstairs?
"Is ROOM upstairs?"
[room]
(#{:library :upstairs-bedroom} room))
(defn on-stairs?
"Is ROOM on the stairs?"
[room]
(#{:front-stairs :back-stairs} room))
(defn where
"A description of Robbie's current location."
[]
(cond
(on-stairs? @loc) (str "robbie is on the " (name @loc))
(upstairs? @loc) (str "robbie is upstairs in the " (name @loc))
:else (str "robbie is downstairs in the " (name @loc))))
(defn move
"If possible, move Robbie in DIRECTION and describe his new location."
[direction]
(if-let [room (look direction @loc)]
(do
(where)
(set-robbie-location room))
"ouch! robbie hit a wall"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment