,r1 \ netc /\ skng t l Figure 3,1 Tree representation of the list - - PowerPoint PPT Presentation

r1
SMART_READER_LITE
LIVE PREVIEW

,r1 \ netc /\ skng t l Figure 3,1 Tree representation of the list - - PowerPoint PPT Presentation

Lists in Prolog 3.1 Representation of lists 61 ann ,/\ tennis ,r1 \ netc /\ skng t l Figure 3,1 Tree representation of the list I ann, tennis, tom, skiing] combined into a structure by the functor '.' .(ann, .(tennis,


slide-1
SLIDE 1

Lists in Prolog

3.1 Representation of lists 61

,/\

ann

tennis

net¡c

,r1 \

/\

lists, one of the simplest and most

erations on lists. We will also look

ich often improves the readability

ith these three additions, becomes

rams.

r non-numeric programming. A

s ann, tennis, tom, skiing. Such a

Сntax for standard Prolog terms

seen in Chapter 2, all structured

:o this.

Prolog obiect? We have to con-

  • Lpty. In the first case, the list is

td case, the list can be viewed as

  • bject -a constant, a variable, a

.. The head and the tail are then

sküng

t l

Figure 3,1 Tree representation of the list I ann, tennis, tom, skiing]

combined into a structure by the functor '.'

.( Head, Tail) Since Tail is in turn a list, it is either empty or it has its own head and tail. Therefore,

to represent lists of any length, no additional principle for structuring objects is

  • needed. Our example list is represented in the standard Prolog notation as the tetm:

.( ann, .( tennis, .( tom, .( skiing, t I ) ) ) )

Figure 3.1 shows the corresponding tree structure. Note that the empty list appears

in this tree. This is because the one but last tail is a single item list:

I skiing]

This list has the empty list as its tail:

I skiing] : .( skiing, [ ] )

This example shows how the general principle for structuring data objects in Prolog

also applies to lists of any length. As our example also shows, however, the standard

notation with dots and possibly deep nesting of subterms in the tail can produce

rather confusing expressions. This is the reason why Prolog provides the friendlier

notation for lists, so that they can be written as sequences of items enclosed in

square brackets. A programmer can use both notations, but the square bracket

notation is, of course, normally preferred. we will be aware, however, that this is

  • nly a cosmetic improvement and that our lists will be in any case internally

represented as binary trees. when such terms are output they are automatically

converted into the list notation. Thus the following conversation with Prolog is

possible:

?- [a,b,c] : .(a, .(b, .(c, []))). yes

?- Listl : [a,b,c], List2 : .( a, .( b, .( c, t I ) ) ).

11511 : [a,b,c]

1¡s12 : [a,b,c]

?- Hotrbiesl : .( tennis, .( music, [ ] ) ),

Hobbies2 : I skiing, food], L : I ann, Hobbiesl, tom, Hobbies2].

‘.’(ann, ‘.’(tennis, ‘.’(tom, ‘.’(skiing, []))))

slide-2
SLIDE 2

3.2.2

3.2 Some operations on lists 65

Concatenation

For concatenating lists we will define the relation:

conc( Ll, L2, L3) Here L1 andL2 are lists, and L3 is their concatenation. For example, conc( [a,b], [c,d], [a,b,c,d] ) is true, but conc( [a,b], [c,d], [a,b,a,c,d] )

is false. In the definition of conc we will have again two cases, depending on the first argument, Ll:

(1) If the first argument is the empty list then the second and the third arguments

must be the same list (call it L); this is expressed by the following Prolog fact:

conc( [ ], L, L).

(2) If the first argument of conc is a non-empty list then it has a head and a tail and

must look like this:

lx lrll

Figure 3.2 illustrates the concatenation of [X I L1] and some listL2. The result

  • f the concatenation is the list [X I L3] whe¡e L3 is the concatenation of Ll and
  • L2. In Prolog this is written as:

conc( [X I LIl, L2, [x I L3] ) :- conc( LL, L2, L3).

This program can now be used for concatenating given lists, for example:

?- conc( la,b,cl, 1L,2,3f, L).

L: la,b,c,l,2,3f

?- conc( [a,þ,c],d1, [a,[ ],b1, L).

L : [a, [b,c], d, a, [ ], b]

tx lLll

L3

lx lL3l

Figure 3.2 Concatenation of lists. efer the program also to generate

Prolog never gets to alternative

ler in which the solutions are

.d, then b as the second element

ists that contain c are generated.

ations instead? Yes, we iust have

three elements

imple word-by-word translation t a dictionary be represented as a

e form

1e query to Prolog. We can then

. with the query:

)1, o/o A small dictionary

  • /o Translate two into Spanish

%o Translate tres into English

:

dure? This can be easily worked

member( d, [a,b,c,d,e,{l). In this

called on lists [b,c,d,e,fl, then

cceeds by the first clause of

t is easy to see that the member

sought for is encountered as the

  • mplexity is linear in the length

to represent a large dictionary

  • es not matter.

x

L1

L2

x

L3

slide-3
SLIDE 3

70 Chapter 3 Lists, Operators, Arithmetic

L

member( X, L)

tx lL2l

sublist( S, L)

Figure 3.4 The member and sublist relations.

is not. The Prolog program for sublist can be based on the same idea as memberl,

  • nly this time the relation is mo¡e general (see Figure 3.4). Accordingly, the relation

can be formulated as:

S is a sublist of L if:

(1) L can be decomposed into two lists, Ll and L2, and, (2) L2 can be decomposed into two lists, S and some L3.

As we have seen before, the conc relation can be used for decomposing lists. So the

above formulation can be expressed in Prolog as: sublist( S, L) :-

conc(LI,L2,L),

conc( S, L3, L2).

  • f course, the sublisr procedure can be used flexibly in several ways. Although it was

designed to check if some list occurs as a sublist within another list it can also be

used, for example, to find all the sublists of a given list:

?- sublist( S, [a,b,c] ).

s:[];

S: [a];

S : [a,b];

5 : [a,b,c];

s:[];

s : [b];

3.2.6 Permutations

Sometimes it is useful to generate permutations of a given list. To this end, we

will define the permutation relation with two arguments. The arguments are two

lists such that one is a permutation of the other. The intention is to generate

L

L2

insert X obtain

Figure 3.5 One way

permutations of a

in the following e:

?- permutation( [

p: [a,b,c]; p: [a,c,b]; p: [b,a,c];

The program for p,

flrst list:

(1) If the first list (2) If the first list

such a list can L1 and then ir Prolog clauses that permutation( [ ], permutation( [X permutation( I insert( X, L1, P One alternative to

permute the rest

corresponding pro permutation2( [ permutation2( L,

del( X, L, L1),

permutation2(

It is instructive to c

use would be some

L1

L2

x

LI

s L3

?- permutation( [

slide-4
SLIDE 4

3.2 Some operations on lists 71

member( X, L) sublist( S, L)

  • n the same idea as memberl,

r 3.4). Accordingly, the relation

,2, and

;ome L3.

d for decomposing lists. So the n several ways. Although it was

lhin another list it can also be

list:

' a given list. To this end, we

  • nents. The arguments are two

The intention is to generate

permute L

L1 is a permutation of L

insert X obtaining a permutation of t X I L l

Figure 3.5 One way of constructing a permutation of the list tX I Ll

permutations of a list through backtracking using the permutation procedure, as

in the following example:

?- permutation( [a,b,c], P).

p: [a,b,c]; p: [a,c,b]; p: [b,a,c];

The program for permutation can be, again, based on two cases, depending on the frrst list:

(1) If the fi¡st list is empty then the second list must also be empty. (2) If the first list is not empty then it has the form [X I L], and a permutation of

such a list can be constructed as shown in Figure 3.5: first permute L obtaining

Ll and then insert X at any position into Ll.

Prolog clauses that coüespond to these two cases are:

permutation(tl,[]).

permutation( [X I L], P) :- permutâtion( L, L1), insert( X, Ll, P).

  • ne alternative to this program would be to delete an element, x, from the first list,

permute the rest of it obtaining a list P, and then add X in front of p. The

corresponding program is:

permutation2(ll, tl).

permutation2( L, [X I P] ) :-

del( X, L, L1),

permutation2( Ll, P).

It is instructive to do some experiments with our permutation programs. Its normal

use would be something like this:

?- permutation( [red,blue,green], P).

slide-5
SLIDE 5

The is operator Forces evaluation. Similar to the assignment statement. The left argument is a simple object.

slide-6
SLIDE 6

ith an operator except in special

ction, they only introduce new

her components of structures.

  • rs. Each operator is defined by

e, usually between 1 and 1200.

the expression is the principal

: precedence bind strongest.

(1) the position of the operator

precedence of the arguments

  • itself. In a specifler like xfy, x

trictly lower than that of the

:nce is less than or equal to that al objects:

eyball

are their principal functors and

s','o1','the') to be able to write

  • :":

'':ir::i='

3.4 Arithmetic 79

How will this program answer the following questions if ,+, is an infix operator of type yfr( (as usual):

(a) ?- t( O+1, A). (b) ?- t( o+1+1, B).

(c) ?- t( 1+O+1+1+1, C).

(d) ?- r( D, 1+1+1+0).

3.f 5 In the previous section, relations involving lists were written as:

member( Element, List), . conc( Listl, List2, List3), del( Element, List, Newlist),... Suppose that we would prefer to write these relations as: Element in List, concatenating Listl and List2 gives List3,

deleting Element from List gives Newlist,...

Define 'in', 'concatenating', 'and', etc. as operators to make this possible. Also,

redefine the corresponding procedures.

Arithmetic

Some of the predefined operators can be used for basic arithmetic operations.

These are:

+

addition

subtraction

*

multiplication

/

division

**

power

ll

integer division

mod

modulo, the remainder of integer division Notice that this is an exceptional case in which an operator may in fact invoke an

  • peration. But even in such cases an additional indication to perform arithmetic

will be necessary. The following question is a naive attempt to request arithmetic

computation:

?- X:'L + 2.

Prolog will simply answer

X:l+2

and not x : 3 as one might possibly expect. The reason is simple: the expression,

1 + 2 merely denotes a Prolog term where -l is the functor and 1 and 2 are its

  • arguments. The operator ':' in the question above just requires the matching of X

and 1 + 2. There is nothing in the question to force Prolog to actually carry out the

slide-7
SLIDE 7

is provided to circumvent this

r the way to actgally invoke

lure that is associated with the

es, or built-in predicates.

newhat different notations for

he operator // denotes integer 3ly, the question:

ject - a variable or a number.

)n composed of arithmetic

will force the evaluation of

  • n will be matched with the

expression must already be

Ê this goal. The precedence of

s such that the associativity of

  • mathematics. Parentheses can
  • n. Note that +, -, *, I and // are

ied out ftom left to right. For

functions such as sin(X),

rs can appear to the right of Lmerical values. We can, for

is greater than 10000 by the

the evaluation.

3.4 Arithmetic 81 Suppose that we have in the program a relation born that relates the names of

people with their birth years. Then we can retrieve the names of people born

between 1980 and 1.990 inclusive with the following question:

?- bom( Name, Year),

Year >

Year <

The comparison operators are as follows:

X>Y

x<Y X>:Y X:<Y X:::Y X:\:Y

X is greater than Y X is less than Y X is greater than or equal to Y X is less than or equal to Y the values of X and Y are equal the values of X and Y are not equal

Notice the difference between the matching operator ':' aîd.'-:-'; fot example, in the goals X : Y and X ::: Y. The frrst goal will cause the matching of the objects X

and Y, and will, if X and Y match, possibly instantiate some variables in X and Y.

There will be no evaluation. On the other hand, X ::: Y causes the arithmetic evaluation and cannot cause any instantiation of variables. These differences are illustrated by the following examples:

?-l+2:::2-ll.

yes

?-l+2:2+1.

no

?-1+A:B+2.

A:2 B:1

Let us further illustrate the use of arithmetic operations by two simple exam-

  • ples. The first is computing the greatest common divisor; the second is counting

the items in a list. Given two positive integers, X and Y, their greatest. common

divisor, D, can be found according to three cases:

(1) If X and Y are equal then D is equal to X.

(Z) If X < Y then D is equal to the greatest common divisor of X and the difference

Y-X.

(3) If Y < X then do the same as in case (2) with X and Y interchanged.

It can be easily shor,rm by an example that these three rules actually work.

Choosing, for example, X : 20 and Y : 25, the above rules would give D : 5 after

a sequence of subtractions.

These rules can be formulated into a Prolog pro$am by defining a three-argument

relation, say:

gcd( X, I D)