/* CLP(R) EXAMPLES FOR 341 LECTURE */ /* This file is on ~borning/clpr/myprogs/lecture.clpr on attu */ /* THE DOUBLE RELATION */ double(X,Y) :- Y=2*X. /* CENTIGRADE-FAHRENHEIT TEMPERATURE CONVERSION */ cf(C,F) :- 1.8*C = F-32.0. /* the same program in Scheme - note that we need two versions: (define (c-to-f c) (+ (* 1.8 c) 32.0)) (define (f-to-c f) (/ (- f 32.0) 1.8)) */ /* FIND THE MAX OF TWO NUMBERS */ max(X,Y,X) :- X>=Y. max(X,Y,Y) :- X= x y) x y)) in Miranda: max x y = x, if x>=y = y, if x0, length(Xs,N-1). /* Miranda version of length: length [] = 0 length (a:as) = 1 + length as */ /* SUM OF THE ELEMENTS IN A LIST */ sum([],0). sum([X|Xs],X+S) :- sum(Xs,S). /* FACTORIAL */ factorial(0,1). factorial(N,N*F) :- N>0, factorial(N-1,F). /* CLAUSES TO FIND ALL PERMUTATIONS OF A LIST */ permute([],[]). permute([H|T],L) :- permute(T,U), insert(H,U,L). /* insert an element X somewhere in list L */ insert(X,L,[X|L]). insert(X,[H|T],[H|U]) :- insert(X,T,U). /* amazingly inefficient sort */ sort(L,S) :- permute(L,S), sorted(S). sorted([]). sorted([X]). sorted([A,B|R]) :- A<=B, sorted([B|R]). /* Miranda version of permute (returns a list of lists, rather than backtracking through multiple lists) perms [] = [[]] perms x = [ a:y | a <- x; y <- perms (x--[a]) ] */ /* QUICKSORT */ quicksort([],[]). quicksort([X|Xs],Sorted) :- partition(X,Xs,Smalls,Bigs), quicksort(Smalls,SortedSmalls), quicksort(Bigs,SortedBigs), append(SortedSmalls,[X|SortedBigs],Sorted). partition(Pivot,[],[],[]). partition(Pivot,[X|Xs],[X|Ys],Zs) :- X <= Pivot, partition(Pivot,Xs,Ys,Zs). partition(Pivot,[X|Xs],Ys,[X|Zs]) :- X > Pivot, partition(Pivot,Xs,Ys,Zs). /* cut (written !) prunes the search tree */ member_cut(X,[X|Xs]) :- !. member_cut(X,[Y|Ys]) :- member(X,Ys). /* member(1,[1,2,3,1]) will succeed twice member_cut(1,[1,2,3,1]) will succeed just once member_cut(X,[1,2,3]) will only give one answer: X=1. */ /* Naive flatten: */ flatten([],[]) :- !. flatten([X|Xs],Y) :- !, flatten(X,XF), flatten(Xs,XsF), append(XF,XsF,Y). flatten(X,[X]). /* Flatten using difference lists: */ dflatten(S,F) :- flatten_dl( S , dl(F,[]) ). flatten_dl( [] , dl(X,X) ) :- !. flatten_dl( [X|Xs] , dl(Y,Z) ) :- !, flatten_dl( X , dl(Y,T) ), flatten_dl( Xs , dl(T,Z) ). flatten_dl( X , dl([X|Z],Z) ).