Tutorial 3

TOPICS
List Operations and manipulations
operation on function terms
Predicates that return function terms

------------------------------------
LIST OPERATIONS AND MANIPULATIONS

add(X,L,[X|L]).
ie. add(a,[b],L).
L=[a,b]

predicates that determine if the length of the list is even or odd.
evenlength([1,2,3]).
no
oddlength([1,2,3]).
yes

evenlength([]).  %base case empty list
evenlength([F|R]):-oddlength(R).

oddlength([_]).  %base case one element.
oddlength([F|R]):-evenlength(R).

trace oddlength([1,2,3]).
F/1 R/[2,3]
evenlength([2,3]).
F/2 R/[3]
oddlength([3]) yes

Define dividelist(L,L1,L2)
so that the elements of L are partitioned between L1, L2, L1 L2 are about the
same length.

ie.  dividelist([a,b,c,d,e],[a,c,e],[b,d]).

dividelist([],[],[]).  %empty list
dividelist([X],[X],[]). %one element
dividelist([X,Y|L],[X|L1],[Y|L2]):-dividelist(L,L1,L2).

Find the maximum element in a list
max(X,Y,X):-X>=Y.
max(X,Y,Y):-X<Y.

maxlist([X], X).        % max of a single element in list
maxlist([X,Y|R], M):-   % atleast 2 elements in list
        maxlist([Y|R],MR),
        max(X,MR,M).    % M is greater of X and MR

Define translate(L1, L2) to translate a list of numbers between 0 and 2 to a 
list of corresponding words.

translate([2,1,2], [two, one, two]).
m(0,zero). m(1,one). m(2,two).

translate([],[]).
translate([X|L1], [Y|L2]):-m(X,Y),translate(L1, L2).
---------------------------------------------------------------------

OPERATIONS ON FUNCTIONS

volume(sphere(R),V):-V is 4/3*3.14*R*R*R.
volume(cube(L),V):-V is L*L*L.
volume(cylinder(R,L)):-V is 3.14*R*R*L.

Compute the volume of a list of  geometric figures

ie. total([cube(1),cube(2),sphere(3),cylinder(2,4)],V)

total([],0).
total([F|L],V):-volume(F,X),total(L,Y),V is X+Y.

____________________________________________________________________
RETURN FUNCTION TERMS

Given a pt p(x,y) return a new pt with 3 less than the coordinates

ie. three(p(1,2),P).
P=p(-2,-1).

three(p(X1,Y1),p(X2,Y2)):-
        X2 is X1-3, X2 is Y1-3.

sub1(X,A,B,Y) that is true iff V is result of replacing every occurence

sub1(p(a,a), a,b,Y).
Y=p(b,b).
sub1(p(c,c),a,b,Y).
Y=p(c,c).
sub1(p(a,p(a,b)),a,b,Y).
Y=p(b,p(b,b))

sub1(A,A,B,B) :- atom(A).
sub1(C,A,_,C) :- atom(C), not(C=A).
sub1(p(X,Y),A,B,p(X1,Y1)) :- sub1(X,A,B,X1), sub1(Y,A,B,Y1).

