Skip to content

Instantly share code, notes, and snippets.

@ecmendenhall
Last active December 17, 2015 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ecmendenhall/5646594 to your computer and use it in GitHub Desktop.
Save ecmendenhall/5646594 to your computer and use it in GitHub Desktop.
Network closures in Clojure, from Chapter 6 of "On Lisp."
;; Figure 6.2 – Representation and definition of nodes
(def nodes (atom {}))
(defn defnode [name contents & [yes no]]
(swap! nodes assoc name {:contents contents :yes yes :no no}))
;; Figure 6.3 – Sample network
(defn make-nodes [node-maker]
(node-maker :people "Is the person a man?" :male :female)
(node-maker :male "Is he living?" :live :dead)
(node-maker :dead "Was he from the USA?" :USA :elsewhere)
(node-maker :USA "Is he on a coin?" :coin :no-coin)
(node-maker :coin "Is the coin a penny?" :penny :other-coin)
(node-maker :penny "Abraham Lincoln."))
;; Figure 6.4 – Function for traversing networks
(defn run-node [name]
(let [node (@nodes name)
contents (node :contents)
yes (node :yes)
no (node :no)]
(if yes
(do
(println contents)
(if (= "yes" (read-line))
(run-node yes)
(run-node no)))
(println contents))))
;; Figure 6.5 - A network compiled into closures
(defn def-closure-node [name contents & [yes no]]
(swap! nodes assoc name
(if yes
(fn []
(println contents)
(if (= "yes" (read-line))
((@nodes yes))
((@nodes no))))
(fn []
(println contents)))))
@thisiswei
Copy link

ecmendenhall, how is going?
Have you read any of peter norvig's book?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment