% demonstration of some mapping operations and list operations. % S. Tanimoto, CSE 341, Spring 2003. % Define a test list: mylist([a,b,c,d,e]). % Here is a predicate that "maps" a function onto elements of a list. % Note that the function is really just a newly constructed term, % and that no evaluation of such a function is performed. mapf([],[]). mapf([X|L], [f(X)|M]) :- mapf(L,M). ?- mylist([H|T]). ?- mylist([H|H]). ?- mylist(L1), mapf(L1, L2). ?- mapf(L1, [f(1),f(2),f(3)]). % Now let's show definitions for last, butlast, and reverse. % Note that last and reverse are built into SWI Prolog. mylast(X, [X]). mylast(X, [H|T]) :- mylast(X, T). butlast([],[A]). butlast([H|T], [H|L]) :- butlast(T,L). myreverse([],[]). myreverse([H|T], L) :- mylast(H, L), butlast(L2, L), myreverse(T, L2). % Here is a mapping predicate that can actually evaluate something % at each element of a list. mapp(Pred, [],[]). mapp(Pred, [H1|T1], [H2|T2]) :- Q =..[Pred,H1, H2],call(Q), mapp(Pred, T1, T2). plusone(X, Y) :- Y is X + 1. % mapp(plusone, [1,2,3], L) % -> L = [2,3,4]. % =.. is called the "univ" operator. It constructs a goal from % a predicate, an input term, and a variable to be instantiated to % give the "output".