PERL   17

# list pl

Guest on 16th August 2022 01:05:22 AM

1. % demonstration of some mapping operations and list operations.
2. % S. Tanimoto, CSE 341, Spring .
3.
4. % Define a test list:
5. mylist([a,b,c,d,e]).
6.
7. % Here is a predicate that "maps" a function onto elements of a list.
8. % Note that the function is really just a newly constructed term,
9. % and that no evaluation of such a function is performed.
10. mapf([],[]).
11. mapf([X|L], [f(X)|M]) :- mapf(L,M).
12.
13. ?- mylist([H|T]).
14.
15. ?- mylist([H|H]).
16.
17. ?- mylist(L1), mapf(L1, L2).
18.
19. ?- mapf(L1, [f(1),f(2),f(3)]).
20.
21. % Now let's show definitions for last, butlast, and reverse.
22. % Note that last and reverse are built into SWI Prolog.
23.
24. mylast(X, [X]).
25. mylast(X, [H|T]) :- mylast(X, T).
26.
27. butlast([],[A]).
28. butlast([H|T], [H|L]) :- butlast(T,L).
29.
30. myreverse([],[]).
31. myreverse([H|T], L) :- mylast(H, L), butlast(L2, L), myreverse(T, L2).
32.
33. % Here is a mapping predicate that can actually evaluate something
34. % at each element of a list.
35.
36. mapp(Pred, [],[]).
37. mapp(Pred, [H1|T1], [H2|T2]) :-
38.  Q =..[Pred,H1, H2],call(Q), mapp(Pred, T1, T2).
39.
40. plusone(X, Y) :- Y is X + 1.
41.
42. % mapp(plusone, [1,2,3], L)
43. % ->    L = [2,3,4].
44.
45. % =..   is called the "univ" operator. It constructs a goal from
46. %       a predicate, an input term, and a variable to be instantiated to
47. %       give the "output".