/* Filename: list2.pro * * Programmer: Br. David Carlson * * Reference: Adapted from Keith Weiskamp's "What's in a List?" from * the May/June 1988 TURBO TECHNIX. * * Date: August 2, 1988 * * Revised: December 17, 1999 to run under yap. * * Description: * * This program contains a number of list-processing predicates for * demonstration purposes. The user must type in a goal to try out one of * these predicates. The first is head_tail which can be used to find the * head and tail of a given list or which can construct a list from a given * head and tail. A printout of a list showing the head and tail at each * stage can be generated using print_list. Index is used to find the * element in the list at a given position (much like array indexing). * Append is used to append two lists into one long list. It can also be * used in the reverse sense: to split a list into component lists. * The reverse predicate can be used to produce a list in reverse order from * the original. Finally, the member predicate is used to tell if a given * item is a member of a certain list or to generate all members of a given * list. */ head_tail(Head, Tail, [Head | Tail]). print_list([]). /* do nothing to print the empty list */ print_list([Head | Tail]) :- write('The first element is: '), write(Head), nl, write('The rest of the list is: '), write(Tail), nl, print_list(Tail). /* Arg 2 must be a bound value, not a free variable. */ index([Head | _], 1, Head). index([_ | Tail], Position, Element) :- Position > 1, NewPosition is Position - 1, index(Tail, NewPosition, Element). append([], List, List). /* [] + List = List */ append([Head | Tail], SecondList, [Head | Rest]) :- append(Tail, SecondList, Rest). /* Call reverse with a bound value for the first arg. */ reverse([], []). reverse([Head | Tail], Result) :- reverse(Tail, Temp), append(Temp, [Head], Result). member(Item, [Item | _]). member(Item, [Head | Tail]) :- member(Item, Tail).