;;; -*- Mode: Lisp; Syntax: Common-Lisp; -*- File: search/algorithms/and-or.lisp

;;;; AND-OR Search in Nondeterministic Environments

;;; A nondeterministic problem gives, for a state and an action, the list
;;; of states the action may lead to.  Its subtypes define methods for
;;; NONDETERMINISTIC-ACTIONS and NONDETERMINISTIC-RESULTS, and for
;;; GOAL-TEST if the goal is not a single state.
;;;
;;; A conditional plan is either nil (the empty plan: we are at a goal) or
;;; a list (action outcomes), where outcomes is an alist from each state the
;;; action may lead to, to the conditional plan to follow in that state.

(defstructure (nondeterministic-problem (:include problem))
  "A problem whose actions may have several outcomes.")

(defmethod nondeterministic-actions ((problem nondeterministic-problem) state)
  "Return the list of actions applicable in this state."
  (declare-ignore state)
  (error "You need to define NONDETERMINISTIC-ACTIONS for ~A" problem))

(defmethod nondeterministic-results ((problem nondeterministic-problem)
				     state action)
  "Return the list of the states that ACTION may lead to from STATE."
  (declare-ignore state action)
  (error "You need to define NONDETERMINISTIC-RESULTS for ~A" problem))

(defun and-or-graph-search (problem)
  "Return a conditional plan that reaches a goal whatever the outcomes of
  the actions, or :failure. [Fig. 4.10]"
  (and-or-or-search problem (problem-initial-state problem) nil))

(defun and-or-or-search (problem state path)
  "OR node: find one action whose every outcome can be solved."
  (cond ((goal-test problem state) nil)
	((member state path :test #'equal) :failure)
	(t (dolist (action (nondeterministic-actions problem state) :failure)
	     (let ((plan (and-or-and-search
			  problem
			  (nondeterministic-results problem state action)
			  (cons state path))))
	       (unless (eq plan :failure)
		 (return (list action plan))))))))

(defun and-or-and-search (problem states path)
  "AND node: find a plan for each of the possible STATES."
  (let ((plans nil))
    (dolist (s states (nreverse plans))
      (let ((plan (and-or-or-search problem s path)))
	(when (eq plan :failure) (return :failure))
	(push (cons s plan) plans)))))

(defun and-or-plan-succeeds? (problem state plan)
  "Does the conditional PLAN reach a goal from STATE, for every outcome?"
  (cond ((goal-test problem state) t)
	((or (eq plan :failure) (null plan)) nil)
	(t (let ((action (first plan))
		 (outcomes (second plan)))
	     (every #'(lambda (s)
			(let ((entry (assoc s outcomes :test #'equal)))
			  (and entry
			       (and-or-plan-succeeds? problem s (cdr entry)))))
		    (nondeterministic-results problem state action))))))
