/* CLP(R) EXAMPLES FOR 341 LECTURE */ /* This file is on ~borning/clpr/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)) */ /* SOME SAMPLE LIST MANIPULATION PROGRAMS */ append([],Ys,Ys). append([X|Xs],Ys,[X|Zs]) :- append(Xs,Ys,Zs). /* Scheme and Haskell versions of append: (define (append x y) (if (null? x) y (cons (car x) (append (cdr x) y)))) append [] y = y append (x:xs) y = x : append xs y */ member(X,[X|Xs]). member(X,[Y|Ys]) :- member(X,Ys). /* Scheme and Haskell versions of member. In these languages we return true or false, while in CLP(R) there is no explicit return value; rather, we succeed or fail. (define (member x xs) (cond ((null? xs) #f) ((eq? x (car xs)) #t) (else (member x (cdr xs))))) member x [] = False member x (x:xs) = True member x (y:xs) = member x xs */ /* LENGTH OF A LIST */ length([],0). length([_|Xs],N) :- N>0, length(Xs,N-1). /* Haskell 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]). /* Haskell version of permute (returns a list of lists, rather than backtracking through multiple lists) perms [] = [[]] perms x = [ a:y | a <- x, y <- perms (remove a x) ] remove a [] = [] remove a (x:y) | a==x = remove a y | otherwise = x : remove a y */ /* 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).