/* ?- myreverse(A,B). B will be the reverse of A */ myreverse([],[]). /* reverse of an empty list an empty list */ myreverse([First|Rest], ReversedList) :- myreverse(Rest, RestReversed), append(RestReversed, [First], ReversedList). /* "Declarative programming: To reverse a non-empty list, reverse the Rest of the list (recursive) to RestReversed. Then append the RestReversed to the list of the First element to obtain the ReversedList. */ /* prolog ?- [examples]. ?- myreverse([1,2,3,a,s,df,'x',"y"],X). X = [[121],x,df,s,a,3,2,1] */ square(X, SquareX) :- SquareX is X * X. circlearea(Radius, Area) :- square(Radius, RadiusSquared), Area is RadiusSquared*3.14159. /* ?- square(12345.6789, X). X = 152415787.50190523 ?- circlearea(12345.6789, X). X = 478827913.85811043 */ max(X,Y,X) :- X > Y. /* max of X and Y is X if X > Y is true */ max(X,Y,Y) :- X =< Y. /* max of X and Y is Y if X <= Y is true */ max(X,Y,Z,X) :- X > Y, X > Z, !. /* Max is X if X is bigger than Y and Z. ! means stop looking for more if this rule is satisfied */ max(X,Y,Z,Z) :- X > Y, X =< Z, !. /* Max is Z */ max(X,Y,Z,Z) :- X < Y, X =< Z, !. /* Another combination for Z = Max */ max(_,Y,_,Y). /* Max defaults to Y if no other rules are satisfied */ /* ?- max(13,1,2,X). X = 13 ?- max(13,14,2,X). X = 14 ?- max(13,14,22,X). X = 14 */ maxlist([],Starter, Starter). /* If the list is empty, the max is the starter "seed" value */ maxlist([First|Others], Starter, NewMax) :- Starter > First, %If the Starter is bigger than First maxlist(Others, Starter, NewMax). % in list, keep using starter. maxlist([First|Others], Starter, NewMax ) :- First >= Starter, % Otherwise, if First is bigger, use maxlist(Others, First, NewMax). % First as the new Starter runmaxlist([First|Rest], Max) :- maxlist([First|Rest], First, Max). /* ?- maxlist([1,2,3,45,20,6], 1, X). Here, you provide a Starter X = 45 ?- runmaxlist([1,2,3,45,20,6], X). Here the Starter is First in List X = 45 */ upper(X, UpperCase) :- char_code(X, LowerCaseCode), char_code('A', ACode), char_code('a', LowerACode), Difference is LowerACode - ACode, UpperCaseCode is LowerCaseCode - Difference, char_code(UpperCase, UpperCaseCode). /* ?- upper(b, X). X = 'B' ?- upper(x, X). X = 'X' ?- upper(z, X). X = 'Z' How char_code behaves: ?- char_code(a, X). X = 97 ?- char_code('A', X). X = 65 ?- char_code(X, 65). X = 'A' */ countdown(0) :- write('Blastoff'),nl. countdown(N) :- N1 is N - 1, /* N is N - 1 won't work - it's not true in Prolog */ write(N), nl, countdown(N1). /* | ?- countdown(10). 10 9 8 7 6 5 4 3 2 1 Blastoff */