% ================================================================= :- pred constr(bool). :- mode constr(in). :- ignore constr/1. % ================================================================= % Program. ascending sorting :- pred bubblesort(list(int),list(int)). :- mode bubblesort(in,out). bubblesort(L,L) :- swap(L,L,false). bubblesort(L,SL) :- swap(L,L1,true), bubblesort(L1,SL). :- pred swap(list(int),list(int),bool). % bool is true if a swap has been done :- mode swap(in,out,out). swap([],[],false). swap([X],[X],false). swap([X,Y|Ys],[Y|Zs],true) :- constr(X > Y), cons(X,Ys,XYs), swap(XYs,Zs,B). swap([X,Y|Ys],[X|Zs],B) :- constr(X =< Y), cons(Y,Ys,YYs), swap(YYs,Zs,B). :- pred cons(int,list(int),list(int)). :- mode cons(in,in,out). cons(H,T,[H|T]). % ================================================================= % catamorphism :- pred length(list(int),int). :- mode length(in,out). :- cata length/2-1. length([],L) :- constr((L=0)). length([H|T],L) :- constr( (L=LT+1) ), length(T,LT). % ================================================================= % Contract on bubblesort: :- spec bubblesort(L,S) ==> length(L,CL), length(S,CS) => constr( CL=CS ). % Contract on swap: :- spec swap(LA,LB,ToF) ==> length(LA,CLA), length(LB,CLB) => constr( CLA = CLB ). % Contract on cons: :- spec cons(H,T,HT) ==> length(T,LT), length(HT,LHT) => constr( LHT = LT+1 ). % ================================================================= % Verification. % Property: :- pred ff1. ff1 :- constr(~(CL = CS)), length(L,CL), length(S,CS), bubblesort(L,S). :- pred ff2. ff2 :- constr( ~(CLA = CLB) ), length(LA,CLA), length(LB,CLB), swap(LA,LB,true). :- pred ff3. ff3 :- constr( ~(LHT = LT+1) ), length(T,LT), length(HT,LHT), cons(H,T,HT). % ================================================================= % NON-CATA predicates: bubblesort cons constr swap