Processing lists in Prolog - 2 - University of Birmingham

06-25433 ¨C Logic Programming

Processing lists in Prolog - 2

This lecture shows that techniques

introduced before (analysing terminating

conditions and recursive programming) can

be used to develop more complex

procedures.

06-25433 ¨C Logic Programming

This lecture is about:

¨C writing procedures with one or more terminating

or recursive clauses;

¨C deleting one or all instances of an element from a

list;

¨C The effects of matching v. unification;

¨C changing the order in which solutions are

presented by changing clause order.

8 - Processing lists in Prolog: 2

1

06-25433 ¨C Logic Programming

Last time:

Terminating at the end of the list

For instance counting all elements:

Terminates at the

end of the list.

% 1 - terminating

count_elem([], Total, Total).

% 2 - recursive

count_elem([Hd|Tail], Sum, Total) :Sum1 is Sum + 1,

count_elem([Hd|Tail], Sum1, Total).

8 - Processing lists in Prolog: 2

2

06-25433 ¨C Logic Programming

Last time:

Terminating when given element is found

For instance finding a given element:

% 1 - terminating

elem(Elem, [Elem|_]).

% 2 - recursive

elem(Elem, [_|Tail]) :elem(Elem, Tail).

Terminates before

the end of the list.

Notice, this can be run ¡°backwards¡± to enumerate the

individual elements of a list.

Demo1

8 - Processing lists in Prolog: 2

3

06-25433 ¨C Logic Programming

Last time: Terminating when given

number of elements have been scanned

% 1 ¨C recursive

nth(Count, Item, [_|Tail]) :Count > 1,

Count0 is Count - 1,

nth(Count0, Item, Tail).

% 2 ¨C terminating

nth(1, Head, [Head|_]).

The code

counts down

from the given

position to 1.

Demo2

8 - Processing lists in Prolog: 2

4

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download