;;; -*- Mode: Lisp; Syntax: Common-Lisp; -*- File: logic/algorithms/fol-fc.lisp

;;;; Forward Chaining in First-Order Definite Clause KBs

(defstructure fol-definite-kb
  "A KB of first-order definite clauses: ground atomic facts, and rules
  (=> (and P1 ... Pn) Q) whose variables all appear in P1 ... Pn."
  (facts nil)
  (rules nil))

(defmethod tell ((kb fol-definite-kb) sentence)
  "Add a definite clause (or a conjunction of them) to the KB."
  (dolist (clause (conjuncts (->horn sentence)))
    ;; ->horn turns a fact P into (=> TRUE P)
    (if (eq (arg1 clause) 'true)
	(fol-fc-add-fact kb (arg2 clause))
      (setf (fol-definite-kb-rules kb)
	    (append (fol-definite-kb-rules kb) (list clause)))))
  t)

(defmethod retract ((kb fol-definite-kb) sentence)
  (dolist (clause (conjuncts (->horn sentence)))
    (if (eq (arg1 clause) 'true)
	(deletef (arg2 clause) (fol-definite-kb-facts kb) :test #'equal)
      (deletef clause (fol-definite-kb-rules kb) :test #'equal)))
  t)

(defmethod ask-each ((kb fol-definite-kb) query fn)
  "Call FN on the bindings of each answer to the atomic QUERY found by
  forward chaining."
  (fol-fc-ask-each kb (logic query) fn))

(defun fol-fc-add-fact (kb fact)
  (setf (fol-definite-kb-facts kb)
	(append (fol-definite-kb-facts kb) (list fact))))

(defun fol-fc-ask (kb alpha)
  "Return the bindings of the first answer to the atomic sentence ALPHA, or
  NIL (+fail+) if forward chaining finds none. [Fig. 9.3]"
  (fol-fc-ask-each kb (logic alpha)
		   #'(lambda (bindings)
		       (return-from fol-fc-ask bindings)))
  +fail+)

(defun fol-fc-ask-each (kb alpha fn)
  "Forward chaining [Fig. 9.3], calling FN on the unifier of ALPHA with each
  fact that unifies with it, the facts already in KB first.  The new facts
  are added to KB, so a later query starts from them."
  ;; Unlike the figure, the facts already in KB are tried too, so that a
  ;; query that is already a fact gets an answer.
  (dolist (fact (fol-definite-kb-facts kb))
    (let ((phi (unify fact alpha)))
      (when phi (funcall fn phi))))
  (loop
   (let ((new nil))
     (dolist (rule (fol-definite-kb-rules kb))
       (let ((rule (rename-variables rule)))
	 (fol-fc-match
	  kb (conjuncts (arg1 rule)) +no-bindings+
	  #'(lambda (theta)
	      (let ((q (subst-bindings theta (arg2 rule))))
		(unless (or (fol-fc-known? q (fol-definite-kb-facts kb))
			    (fol-fc-known? q new))
		  (push q new)
		  (let ((phi (unify q alpha)))
		    (when phi (funcall fn phi)))))))))
     (when (null new) (return nil))
     (dolist (fact (nreverse new))
       (fol-fc-add-fact kb fact)))))

(defun fol-fc-match (kb premises bindings fn)
  "Call FN on each substitution that makes all PREMISES facts of KB."
  (if (null premises)
      (funcall fn bindings)
    (dolist (fact (fol-definite-kb-facts kb))
      (let ((b (unify (first premises) fact bindings)))
	(when b
	  (fol-fc-match kb (rest premises) b fn))))))

(defun fol-fc-known? (sentence facts)
  "Is SENTENCE a renaming of one of the facts?"
  (some #'(lambda (fact) (renaming? sentence fact)) facts))

;;;; The Compiled APPEND Predicate [Fig. 9.8]

;;; The Prolog definition
;;;   Append([], y, y).
;;;   Append([a|x], y, [a|z]) :- Append(x, y, z).
;;; compiled into a Lisp function, as in the figure.  Logic variables are
;;; structures that are bound destructively; every binding is recorded on
;;; *PROLOG-TRAIL*, so that backtracking can undo it.  Prolog lists are Lisp
;;; lists, with NIL as the empty list.

(defvar *prolog-var-counter* 0)

(defstruct (prolog-var (:print-function
			(lambda (v stream depth)
			  (declare (ignore depth))
			  (format stream "_G~D" (prolog-var-id v)))))
  (binding nil)
  (bound? nil)
  (id (incf *prolog-var-counter*)))

(defvar *prolog-trail* (make-array 100 :adjustable t :fill-pointer 0)
  "The logic variables bound so far, most recent last.")

(defun prolog-deref (term)
  "Follow the bindings of a variable to the term it stands for."
  (loop while (and (prolog-var-p term) (prolog-var-bound? term))
	do (setf term (prolog-var-binding term)))
  term)

(defun prolog-bind (var value)
  (setf (prolog-var-binding var) value
	(prolog-var-bound? var) t)
  (vector-push-extend var *prolog-trail*))

(defun prolog-unify (x y)
  "Unify X and Y by binding variables in place (no occurs check).  On
  failure some bindings may remain; the caller undoes them."
  (let ((x (prolog-deref x)) (y (prolog-deref y)))
    (cond ((eql x y) t)
	  ((prolog-var-p x) (prolog-bind x y) t)
	  ((prolog-var-p y) (prolog-bind y x) t)
	  ((and (consp x) (consp y))
	   (and (prolog-unify (car x) (car y))
		(prolog-unify (cdr x) (cdr y))))
	  (t (equal x y)))))

(defun prolog-undo-bindings (mark)
  "Undo the bindings made since the trail had MARK elements."
  (loop while (> (fill-pointer *prolog-trail*) mark)
	do (let ((var (vector-pop *prolog-trail*)))
	     (setf (prolog-var-binding var) nil
		   (prolog-var-bound? var) nil))))

(defun prolog-append (ax y az continuation)
  "Call CONTINUATION once for each way of satisfying Append(AX, Y, AZ).
  [Fig. 9.8]"
  (let ((trail (fill-pointer *prolog-trail*)))
    (when (and (prolog-unify ax nil) (prolog-unify y az))
      (funcall continuation))
    (prolog-undo-bindings trail)
    (let ((a (make-prolog-var)) (x (make-prolog-var)) (z (make-prolog-var)))
      (when (and (prolog-unify ax (cons a x)) (prolog-unify az (cons a z)))
	(prolog-append x y z continuation))
      (prolog-undo-bindings trail))))

(defun prolog-resolve (term)
  "The term with all the bound variables replaced by their values."
  (let ((term (prolog-deref term)))
    (if (consp term)
	(cons (prolog-resolve (car term)) (prolog-resolve (cdr term)))
      term)))

(defun prolog-append-solutions (ax y az)
  "Return the list of all the (ax y az) triples that satisfy Append."
  (let ((solutions nil))
    (prolog-append ax y az
		   #'(lambda ()
		       (push (mapcar #'prolog-resolve (list ax y az))
			     solutions)))
    (nreverse solutions)))
