;;; -*- Mode: Lisp; Syntax: Common-Lisp; -*- File: logic/algorithms/unify-mm.lisp

;;;; Unification by Martelli and Montanari

;;; A. Martelli and U. Montanari, "An Efficient Unification Algorithm",
;;; ACM TOPLAS 4(2), 1982.  Unification is seen as solving a set of
;;; equations between terms, transformed by four rules until it is in solved
;;; form, i.e., a set of equations var = term where no var occurs anywhere else:
;;;   (a) t = x, with t not a variable, becomes x = t;
;;;   (b) x = x is deleted;
;;;   (c) f(s1..sn) = f(t1..tn) becomes s1 = t1, ..., sn = tn, and
;;;       f(...) = g(...) fails;
;;;   (d) x = t, with x not in t, replaces x by t in all the other equations;
;;;       if x occurs in t, it fails (the occurs check).
;;; Terms and variables are as in unify.lisp, and so is the result: a binding
;;; list, +no-bindings+, or +fail+.

(defun unify-mm (x y &optional (bindings +no-bindings+))
  "Unify X and Y (with given bindings) by the Martelli-Montanari rules;
  return the bindings of the solved form, or +fail+."
  (when (eq bindings +fail+)
    (return-from unify-mm +fail+))
  (let ((equations (cons (cons x y)
			 (if (eq bindings +no-bindings+) nil
			   (copy-alist bindings))))
	(solved nil))
    (loop
     (when (null equations)
       (return (or (nreverse solved) +no-bindings+)))
     (destructuring-bind (s . u) (pop equations)
       (cond ((equal s u))		; rule (b)
	     ((variable? s)		; rule (d)
	      (when (mm-occurs-in? s u)
		(return +fail+))
	      (flet ((eliminate (e)
		       (cons (subst u s (car e)) (subst u s (cdr e)))))
		(setf equations (mapcar #'eliminate equations)
		      solved (mapcar #'eliminate solved)))
	      (push (cons s u) solved))
	     ((variable? u)		; rule (a)
	      (push (cons u s) equations))
	     ((and (consp s) (consp u)	; rule (c)
		   (= (length s) (length u)))
	      (setf equations (nconc (mapcar #'cons s u) equations)))
	     (t (return +fail+)))))))

(defun mm-occurs-in? (var term)
  "Does the variable occur in the term?"
  (cond ((eq var term) t)
	((consp term) (or (mm-occurs-in? var (car term))
			  (mm-occurs-in? var (cdr term))))
	(t nil)))
