:- 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. % https://algs4.cs.princeton.edu/32bst/ :- pred bstdelete(int,tree(int),tree(int)). :- mode bstdelete(in,in,out). bstdelete(X,leaf,leaf). % note deleting X from empty tree succeeds. bstdelete(X,node(A,leaf,R), R) :- constr(X=A). bstdelete(X,node(A,L,leaf), L) :- constr(X=A). bstdelete(X,node(A,L,R), node(Succ,L,T) ) :- constr((~(X=A))& IsDef), % error: (~(X=A)) should be (X=A) bstdeletemin(R, T, Succ, IsDef). bstdelete(X,node(A,L,R), node(A,L1,R)) :- constr(X 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) % ---- :- 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 C2=ite(X=Y, 0, C1 ) )), bstree(T1,B1), treecount(Y,T1,C1), treecount(Y,T2,C2), bstdelete(X,T1,T2). :- pred ff2. ff2 :- constr( ~( (IsDef & B1) => C2=ite(Min=Y, 0, C1 ) )), bstree(T1,B1), treecount(Y,T1,C1), treecount(Y,T2,C2), bstdeletemin(T1,T2,Min,IsDef). % ========================================================== :- query ff1/0. :- query ff2/0. % ==========================================================