;;; -*- Mode: Lisp; -*- Author: Peter Norvig

;;;; Knowledge-Based Agent

;;; The generic knowledge-based agent of [Fig. 7.1]: it TELLs the KB what
;;; it perceives, ASKs it what to do, and TELLs it the action it chose.
;;; The three sentences are built by functions of the percept, the action
;;; and the time; by default (Percept p t), (Action $a t) and (Did a t).

(defun make-kb-agent-program (kb &key
				 (make-percept-sentence
				  #'(lambda (percept tick)
				      `(Percept ,percept ,tick)))
				 (make-action-query
				  #'(lambda (tick) `(Action $a ,tick)))
				 (make-action-sentence
				  #'(lambda (action tick)
				      `(Did ,action ,tick))))
  "Return a knowledge-based agent program for KB. [Fig. 7.1]  The action
  query must contain the variable $a, which ASK binds to the action."
  (let ((clock 0))
    #'(lambda (percept)
	(tell kb (funcall make-percept-sentence percept clock))
	(let ((action (ask-pattern kb (funcall make-action-query clock) '$a)))
	  (tell kb (funcall make-action-sentence action clock))
	  (incf clock)
	  action))))

;;; The action-value agent of the 1st edition [p 210] asks for a great,
;;; good, medium or risky action, in that order.

(defun make-action-value-agent-program (&key (kb (make-horn-kb)))
  "Define an action-value knowledge-based agent. [p 210]"
  (let ((clock 0))
    #'(lambda (percept)
	(tell kb `(Percept ,percept ,clock))
	(let ((action (or (ask-pattern kb `(Great $a ,clock) '$a)
			  (ask-pattern kb `(Good $a ,clock) '$a)
			  (ask-pattern kb `(Medium $a ,clock) '$a)
			  (ask-pattern kb `(Risky $a ,clock) '$a))))
	  (tell kb `(Did Self ,action ,clock))
	  (incf clock)
	  action))))

(defstructure (action-value-agent
	       (:include agent (program (make-action-value-agent-program))))
  "An agent with the action-value program, on an empty Horn KB.")
