Last active
December 17, 2015 17:29
-
-
Save ecmendenhall/5646594 to your computer and use it in GitHub Desktop.
Network closures in Clojure, from Chapter 6 of "On Lisp."
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; 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))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ecmendenhall, how is going?
Have you read any of peter norvig's book?