(deffacts tree (node root decision "Is it warm blooded?" n1 n2) (node n1 decision "Does it purr ?" n3 n4) (node n2 answer snake) (node n3 answer cat) (node n4 answer dog) ) ;; initialization rule (defrule init (initial-fact) => (assert (current-node root)) ) (defrule init => (assert (current-node root)) ) ;; rule to request a decision node (defrule make-decision ?N <- (current-node ?name) (node ?name decision ?q ?yes ?no) => (retract ?N) (format t "%s (yes or no) " ?q) (bind ?answer (read)) (if (eq ?answer yes) then (assert (current-node ?yes) ) else (assert (current-node ?no)) ) ) ;; rule to give answers (defrule give-answer ?N <- (current-node ?name) (node ?name answer ?r) => (printout t "I guess that it is a " ?r crlf) (printout t "Am I right? (yes or no) ") (bind ?rep (read)) (if (eq ?rep yes) then (assert (phase play-again)) (retract ?N) else (assert (phase correct-answer)) ) ) ;; rule to play again (defrule play-again ?phase <- (phase play-again) => (retract ?phase) (printout t "play again? (yes or no) ") (bind ?rep (read)) (if (eq ?rep yes) then (assert (current-node root)) else (save-facts "animal.dat") (halt) ) ) ;; rule to learn the correct answer (defrule learn-correct-answer ?P <- (phase correct-answer) ?N <- (current-node ?name) ?D <- (node ?name answer ?r) => (retract ?P ?N ?D) ;; Ask the correct answer (printout t "What animal was it? ") (bind ?new (read)) (printout t "What question should I ask to tell a " ?new " from a " ?r "? ") (bind ?question (readline)) (bind ?newnode1 (gensym*)) (bind ?newnode2 (gensym*)) (assert (node ?newnode1 answer ?new)) (assert (node ?newnode2 answer ?r)) (assert (node ?name decision ?question ?newnode1 ?newnode2)) (assert (phase play-again)) ) ;; Rule to open the file animal.dat (defrule init (initial-fact) => (assert (file (open "animal.dat" data "r"))) ) ;; rule to close the file animal.dat (defrule no-file ?f <- (file FALSE) => (retract ?f) (assert (current-node root)) ) ;; rule to read the file. (defrule init-file ?f <- (file TRUE) => (bind ?in (readline data)) (printout t ?in crlf) (if (eq ?in EOF) then (assert (eof)) else (assert-string ?in) (retract ?f) (assert (file TRUE)) ) ) (defrule eof (declare (salience 30)) ?f <- (file TRUE) ?eof <- (eof) => (retract ?f ?eof) (close data) (assert (current-node root)) )