Skip to content

Instantly share code, notes, and snippets.

@timyates
Created July 22, 2010 10:18
Show Gist options
  • Save timyates/485805 to your computer and use it in GitHub Desktop.
Save timyates/485805 to your computer and use it in GitHub Desktop.
; The "are you thinking of an animal" game from over 2 decades ago, but in clojure
; Tim Yates
; v0.1
; Not sure if storing the brain as a load of refs is the most ideomatic way of doing things
; Also, one of my first full bits of clojure, so might not be the most sensible way of doing
; any of it
(ns animal.core
(:gen-class))
(defn prompt [prompt-text]
"Ask the user for some input, and keep asking till they enter something"
(do
(print (str prompt-text " : "))
(flush)
(let [ans (read-line)]
(if (seq ans)
ans
(recur prompt-text)))))
(defn yes-no [prompt-text]
"Ask the user something, and keep asking till their answer starts with y or n"
(let [ans (.toUpperCase (prompt (str prompt-text " [Yes/No]")))]
(condp = (first ans)
\Y true
\N false
(recur prompt-text))))
(defn new-node [text yes no]
"Generate a new neuron in our brain"
(ref { :text text :yes yes :no no }))
(def brain (new-node "dog" nil nil))
(defn q-and-a [neuron]
"Walk the neurons asking questions till you reach a leaf"
(if (nil? (:yes @neuron))
neuron
(if (yes-no (:text @neuron))
(recur (:yes @neuron))
(recur (:no @neuron)))))
(defn -main [& args]
(while (yes-no "Are you thinking of an animal?")
(let [synapse (q-and-a brain)]
(if (yes-no (str "Is it a " (:text @synapse) "?"))
(println "I Rule!")
(let [animal (new-node (prompt "Give up! What animal were you thinking of?") nil nil)
quest (prompt (str "What yes/no question would differentiate between a " (:text @animal) " and a " (:text @synapse) "?"))
answer (yes-no (str "For a " (:text @animal) " the answer would be?"))
oldani (new-node (:text @synapse) nil nil)
y-node (if answer animal oldani)
n-node (if answer oldani animal)]
(dosync
(alter synapse assoc :text quest)
(alter synapse assoc :yes y-node)
(alter synapse assoc :no n-node)))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment