Skip to content

Instantly share code, notes, and snippets.

@paul-english
Last active August 29, 2015 14:02
Show Gist options
  • Save paul-english/5636a46ccabd3366b717 to your computer and use it in GitHub Desktop.
Save paul-english/5636a46ccabd3366b717 to your computer and use it in GitHub Desktop.
decision-tables.clj
;; http://en.wikipedia.org/wiki/Decision_tables
;; http://rosettacode.org/wiki/Decision_tables
;; this example is ported from the pico lisp example
(defn yes? [condition]
(print (str (first condition) "? "))
(flush)
(loop [reply (read-line)]
(cond
(contains? #{"T" "Y" "YES" "Yes" "y" "yes" "true" "1"} reply) true
(contains? #{"NIL" "N" "NO" "No" "n" "no" "false" "0"} reply) nil
:else (do
(println "Invalid input")
(recur (read-line))))))
(defn extract
"Returns all non-nil results of applyinig fn to args"
[fn & args]
(filter identity (apply (partial map fn) args)))
(defn pick
"Returns the first non-nil result of applying fn to args"
[fn & args]
(first (apply (partial extract fn) args)))
(def conditions
[["printer does not print" true true true true nil nil nil nil]
["a red light is flashing" true true nil nil true true nil nil]
["printer is unrecognised" true nil true nil true nil true nil]])
(def actions
[["check the power cable" nil nil true]
["check the printer-computer cable" true nil true]
["ensure printer software is installed" true nil true nil true nil true]
["check/replace ink" true true nil nil true true]
["check for paper jam" nil true nil true]])
(defn decide
([] (apply decide (doall (map yes? conditions))))
([& input]
(extract #(and %1 %2)
(apply (partial pick (fn [& args]
(when (not (pick #(not= %1 %2)
input (first args)))
(rest args))))
(concat conditions actions))
(map first actions))))
;; : (decide)
;; Printer does not print? y
;; A red light is flashing? y
;; Printer is unrecognised? n
;; -> ("Check/replace ink" "Check for paper jam")
;; : (decide)
;; Printer does not print? n
;; A red light is flashing? y
;; Printer is unrecognised? y
;; -> ("Ensure printer software is installed" "Check/replace ink")
;; : (decide)
;; Printer does not print? n
;; A red light is flashing? n
;; Printer is unrecognised? n
;; -> NIL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment