;; -*- Scheme -*-
;;
;; $Id: avl-tree04.scm,v 1.1 1998/03/16 07:57:15 foner Exp $

;;------------

(require 'avl-tree:make-leaf)
(require 'avl-tree::add)
(require 'avl-tree::data)
(require 'avl-tree::height)
(require 'avl-tree::left)
(require 'avl-tree::make)
(require 'avl-tree::right)

;;------------


;;+doc
;; procedure: avl-tree:merge-insert
;; arguments: tree key unwrap-key <? if-found[old] if-not-found
;; signature: forall a,b,c
;;   => avl-tree[a,b,c] x c x (c -> a) x (a x a -> bool) x (c -> c)
;;    x (() -> c)
;;   -> avl-tree[a,b,c]
;;
;; Insert an element with the given KEY into TREE.  If an element with
;; the same key is already in the tree, IF-FOUND is called with the
;; element already there and it should return either it or the element
;; to be inserted.  If an element with the same key is not in TREE,
;; then IF-NOT-FOUND is called with no arguments and this should
;; return the element to be inserted.
;;-doc

(define avl-tree:merge-insert
  (lambda (t k uk <? if-found if-not-found)
    (let ((merge (lambda (t)
		   (avl-tree::make
		    (avl-tree::left t)
		    (if-found (avl-tree::data t))
		    (avl-tree::height t)
		    (avl-tree::right t))))
	  (add (lambda () (avl-tree:make-leaf (if-not-found)))))
      (avl-tree::add t k uk <? merge add))))

;; eof
