:- pred constr(bool). :- mode constr(in). :- ignore constr/1. :- type tree(int) ---> leaf ; node( int, tree(int), tree(int) ). % empty tree key left-subtree right-subtree % Note: duplicates are NOT allowed. % ========================================================== % Program. % Binary Search Tree - :- pred bstdeletemin(tree(int),tree(int),int,bool). :- mode bstdeletemin(in,out,out,out). bstdeletemin(leaf,leaf,X,IsDef) :- constr(X=0 & ~IsDef). % 0 can be any int value. bstdeletemin(node(A,leaf,R),R,X,IsDef) :- constr(X=A & IsDef). bstdeletemin(node(A,LeftT,R),node(A,T,R),X,IsDef) :- constr(IsDef), bstdeletemin(LeftT,T,X,IsDef). % X is the successor of A in the tree % X is the minimum (and the leftmost node) of the right subtree rooted at A. % ========================================================== % bstree checks whether or not a tree is a binary search tree. :- pred bstree(tree(int),bool). :- mode bstree(in,out). :- cata bstree/2-1. bstree(leaf,B) :- constr(B). % Values increasing left-to-right bstree(node(N,L,R),B) :- bstree(L,BL), bstree(R,BR), treemax(L,IsDefL,MaxL), treemin(R,IsDefR,MinR), constr( ( (GeqLeft=(IsDefL => N>MaxL)) & (LeqRight=(IsDefR => NMaxR, ite(MaxL>N,MaxL,N), ite(MaxR>N,MaxR,N) ), % max(MaxL,max(MaxR,N)) ite(IsDefL, ite(MaxL>N,MaxL,N), % max(MaxL,N) ite(IsDefR & MaxR>N,MaxR,N))))). % max(MaxR,N) % ---- % treemin for ANY binary tree (ok also for trees with duplicate values) :- pred treemin(tree(int),bool,int). :- mode treemin(in,out,out). :- cata treemin/3-1. treemin(leaf,IsDef,Min) :- constr(~IsDef & Min=0). treemin(node(N,L,R),IsDef,Min) :- treemin(L,IsDefL,MinL), treemin(R,IsDefR,MinR), constr(IsDef & (Min= ite(IsDefL & IsDefR, ite(MinL (X=Min1 & Min2>Min1) )), bstree(T1,B1), bstree(T2,B2), treemin(T1,IsDef1,Min1), treemin(T2,IsDef2,Min2), bstdeletemin(T1,T2,X,IsDef1). %========================================================== :- query ff1/0. % ==========================================================