:- 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 % https://algs4.cs.princeton.edu/32bst/ :- pred bstdeletemin(tree(int),tree(int),int,bool). :- mode bstdeletemin(in,out,out,out). % error: X=0 & IsDef should be X=0 & ~IsDef 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). % ========================================================== % 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). % NO duplicates. 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 (SOut=ite(LeafB,SIn,SIn-1))) & (SIn=0 => SOut=0) )), bstree(BstIn,BIn), bstree(BstOut,BOut), treesize(BstIn,SIn), treesize(BstOut,SOut), is_leaf(BstIn,LeafB), bstdeletemin(BstIn,BstOut,Min,IsDef). % ========================================================== :- query ff1/0. % ==========================================================