logic programming - efficient prolog. i/oisabela.dramnesc/lp/lecture5_lp.pdf · tail recursion i if...

Post on 12-Oct-2020

27 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Logic ProgrammingEfficient Prolog. I/O

October 2018

The procedural aspect of Prolog

I While Prolog is described as a declarative language, one cansee Prolog clauses from a procedural point of view:

i n (X, usa ):−i n (X, m i s s i s s i p p i ) .

The above can be seen:I from a declarative point of view: “X is in the USA if X is in

Mississippi”,I from a procedural point of view: “To prove that X is in the

USA, prove X is in Mississippi”, or “To find X in USA, (it issufficient to) find them in Mississippi”.

I Procedural programming languages can also containdeclarative aspects. Something like

x = y + z ;

can be readI declaratively, as the equation x = y + z ,I procedurally: load y , load z , store x .

The need to understand the procedural/declarative aspects

I The declarative/procedural aspects are not “symmetrical”:there are situations where one not understanding one aspectcan lead to problems.

I For procedural programs: A = (B + C) + D andA = B + (C +D) appear to have equivalent declarativereadings but:

I imagine the biggest number that can be represented is 1000,I then for B = 501, C = 501, D = -3, the two expressions yield

totally different results!

I The same can happen in Prolog. Declaratively, the followingis correct:

a n c e s t o r (A, C):−a n c e s t o r (A, B) ,a n c e s t o r (B, C ) .

However, ignoring its procedural meaning, this can lead toinfinite loops (when B and C are both unknown).

I The task of a Prolog programmer is to build a model of theproblem and to represent it in Prolog.

I Knowledge about this model can improve performancesignificantly.

?−horse(X), gray(X). will find the answer much faster than?−gray(X), horse(X). in a model with 1000 gray objects and10 horses.

I Narrowing the search can be even more subtle:

s e t e q u i v a l e n t ( L1 , L2 ):−permute ( L1 , L2 ) .

i.e. to find whether two lists are set-equivalent it is enough tosee whether they are permutations of eachother. But for Nelement lists, there are N! permutations (e.g. for 20 elements,2.4× 1018 possible permutations).

I Now considering a faster program:

s e t e q u i v a l e n t ( L1 , L2 ):−s o r t ( L1 , L3 ) ,s o r t ( L2 , L3 ) .

i.e. two lists are set equivalent if their sorted versions are thesame. And sorting can be done in NlogN steps (e.g. approx86 steps for 20 element lists).

I When patterns are involved, unification can do some of thework that the programmer may have to do.

I E.g. consider variants the predicate that detects lists with 3elements:

I

h a s 3 e l e m e n t s (X):−l e n g t h (X, N) ,N = 3 .

I

h a s 3 e l e m e n t s ( [ , , ] ) .

I Also consider the predicate for swapping the first twoelements from a list:

s w a p f i r s t 2 ( [ A, B | Rest ] , [ B , A | Rest ] ) .

Letting unification work saves having to go through the wholelist.

I Atoms are represented in Prolog in a symbol table where eachatom appears once - a process called tokenization.

I Atoms in a program are replaced by their address in thesymbol table.

I Because of this:

f ( ’ What a l o n g atom t h i s a p p e a r s to be ’ ,’ What a l o n g atom t h i s a p p e a r s to be ’ ,’ What a l o n g atom t h i s a p p e a r s to be ’ ) .

will actually take less memory than g(a, b, c)

I Comparison of atoms can be performed very fast because oftokenization.

I For example a \= b and aaaaaaaaa \= aaaaaaaab can bothbe done in the same time, without having to “parse” thewhole atom names.

I Atoms are represented in Prolog in a symbol table where eachatom appears once - a process called tokenization.

I Atoms in a program are replaced by their address in thesymbol table.

I Because of this:

f ( ’ What a l o n g atom t h i s a p p e a r s to be ’ ,’ What a l o n g atom t h i s a p p e a r s to be ’ ,’ What a l o n g atom t h i s a p p e a r s to be ’ ) .

will actually take less memory than g(a, b, c)

I Comparison of atoms can be performed very fast because oftokenization.

I For example a \= b and aaaaaaaaa \= aaaaaaaab can bothbe done in the same time, without having to “parse” thewhole atom names.

I Atoms are represented in Prolog in a symbol table where eachatom appears once - a process called tokenization.

I Atoms in a program are replaced by their address in thesymbol table.

I Because of this:

f ( ’ What a l o n g atom t h i s a p p e a r s to be ’ ,’ What a l o n g atom t h i s a p p e a r s to be ’ ,’ What a l o n g atom t h i s a p p e a r s to be ’ ) .

will actually take less memory than g(a, b, c)

I Comparison of atoms can be performed very fast because oftokenization.

I For example a \= b and aaaaaaaaa \= aaaaaaaab can bothbe done in the same time, without having to “parse” thewhole atom names.

I Atoms are represented in Prolog in a symbol table where eachatom appears once - a process called tokenization.

I Atoms in a program are replaced by their address in thesymbol table.

I Because of this:

f ( ’ What a l o n g atom t h i s a p p e a r s to be ’ ,’ What a l o n g atom t h i s a p p e a r s to be ’ ,’ What a l o n g atom t h i s a p p e a r s to be ’ ) .

will actually take less memory than g(a, b, c)

I Comparison of atoms can be performed very fast because oftokenization.

I For example a \= b and aaaaaaaaa \= aaaaaaaab can bothbe done in the same time, without having to “parse” thewhole atom names.

I Atoms are represented in Prolog in a symbol table where eachatom appears once - a process called tokenization.

I Atoms in a program are replaced by their address in thesymbol table.

I Because of this:

f ( ’ What a l o n g atom t h i s a p p e a r s to be ’ ,’ What a l o n g atom t h i s a p p e a r s to be ’ ,’ What a l o n g atom t h i s a p p e a r s to be ’ ) .

will actually take less memory than g(a, b, c)

I Comparison of atoms can be performed very fast because oftokenization.

I For example a \= b and aaaaaaaaa \= aaaaaaaab can bothbe done in the same time, without having to “parse” thewhole atom names.

Continuations, backtracking points

I Consider the following:

a:− b , c .a:− d .

I For ?− a., when b is called, Prolog has to save in thememory:

I the continuation, i.e. what has to be done after returning withsuccess from b (i.e. c),

I the backtrack point, i.e. where can an alternative be tried incase of returning with failure from b (i.e. d).

I For recursive procedures the continuation and backtrackingpoint have to be remembered for each of the recursive calls.

I This may lead to large memory requirements

Continuations, backtracking points

I Consider the following:

a:− b , c .a:− d .

I For ?− a., when b is called, Prolog has to save in thememory:

I the continuation, i.e. what has to be done after returning withsuccess from b (i.e. c),

I the backtrack point, i.e. where can an alternative be tried incase of returning with failure from b (i.e. d).

I For recursive procedures the continuation and backtrackingpoint have to be remembered for each of the recursive calls.

I This may lead to large memory requirements

Continuations, backtracking points

I Consider the following:

a:− b , c .a:− d .

I For ?− a., when b is called, Prolog has to save in thememory:

I the continuation, i.e. what has to be done after returning withsuccess from b (i.e. c),

I the backtrack point, i.e. where can an alternative be tried incase of returning with failure from b (i.e. d).

I For recursive procedures the continuation and backtrackingpoint have to be remembered for each of the recursive calls.

I This may lead to large memory requirements

Continuations, backtracking points

I Consider the following:

a:− b , c .a:− d .

I For ?− a., when b is called, Prolog has to save in thememory:

I the continuation, i.e. what has to be done after returning withsuccess from b (i.e. c),

I the backtrack point, i.e. where can an alternative be tried incase of returning with failure from b (i.e. d).

I For recursive procedures the continuation and backtrackingpoint have to be remembered for each of the recursive calls.

I This may lead to large memory requirements

Continuations, backtracking points

I Consider the following:

a:− b , c .a:− d .

I For ?− a., when b is called, Prolog has to save in thememory:

I the continuation, i.e. what has to be done after returning withsuccess from b (i.e. c),

I the backtrack point, i.e. where can an alternative be tried incase of returning with failure from b (i.e. d).

I For recursive procedures the continuation and backtrackingpoint have to be remembered for each of the recursive calls.

I This may lead to large memory requirements

Continuations, backtracking points

I Consider the following:

a:− b , c .a:− d .

I For ?− a., when b is called, Prolog has to save in thememory:

I the continuation, i.e. what has to be done after returning withsuccess from b (i.e. c),

I the backtrack point, i.e. where can an alternative be tried incase of returning with failure from b (i.e. d).

I For recursive procedures the continuation and backtrackingpoint have to be remembered for each of the recursive calls.

I This may lead to large memory requirements

Tail recursion

I If a recursive predicate has no continuation, and nobacktracking point, Prolog can recognize this and will notallocate memory.

I Such recursive predicates are called tail recursive (therecursive call is the last in the clause and there are noalternatives).

I They are much more efficient than the non-tail recursivevariants.

I The following is tail recursive:

t e s t 1 (N):− w r i t e (N) , n l , NewN i s N+1, t e s t 1 (NewN ) .

In the above write writes (prints) the argument on the consoleand succeeds, nl moves on a new line and succeeds. Thepredicate will print natural numbers on the console until theresources run out (memory or number representations limit).

Tail recursion

I If a recursive predicate has no continuation, and nobacktracking point, Prolog can recognize this and will notallocate memory.

I Such recursive predicates are called tail recursive (therecursive call is the last in the clause and there are noalternatives).

I They are much more efficient than the non-tail recursivevariants.

I The following is tail recursive:

t e s t 1 (N):− w r i t e (N) , n l , NewN i s N+1, t e s t 1 (NewN ) .

In the above write writes (prints) the argument on the consoleand succeeds, nl moves on a new line and succeeds. Thepredicate will print natural numbers on the console until theresources run out (memory or number representations limit).

Tail recursion

I If a recursive predicate has no continuation, and nobacktracking point, Prolog can recognize this and will notallocate memory.

I Such recursive predicates are called tail recursive (therecursive call is the last in the clause and there are noalternatives).

I They are much more efficient than the non-tail recursivevariants.

I The following is tail recursive:

t e s t 1 (N):− w r i t e (N) , n l , NewN i s N+1, t e s t 1 (NewN ) .

In the above write writes (prints) the argument on the consoleand succeeds, nl moves on a new line and succeeds. Thepredicate will print natural numbers on the console until theresources run out (memory or number representations limit).

Tail recursion

I If a recursive predicate has no continuation, and nobacktracking point, Prolog can recognize this and will notallocate memory.

I Such recursive predicates are called tail recursive (therecursive call is the last in the clause and there are noalternatives).

I They are much more efficient than the non-tail recursivevariants.

I The following is tail recursive:

t e s t 1 (N):− w r i t e (N) , n l , NewN i s N+1, t e s t 1 (NewN ) .

In the above write writes (prints) the argument on the consoleand succeeds, nl moves on a new line and succeeds. Thepredicate will print natural numbers on the console until theresources run out (memory or number representations limit).

I The following is not tail recursive (it has a continuation):

t e s t 2 (N):− w r i t e (N) , n l , NewN i s N+1,t e s t 2 (NewN) , n l .

When running this, it will run out of memory relatively soon.

I The following is not tail recursive (it has a backtrackingpoint):

t e s t 3 (N):− w r i t e (N) , n l , NewN i s N+1,t e s t 3 (NewN ) .

t e s t 3 (N):− N<0.

I The following is tail recursive (the alternative clause comesbefore the recursive clause so there is no backtracking pointfor the recursive call):

t e s t 3 a (N):− N<0.t e s t 3 a (N):− w r i t e (N) , n l , NewN i s N+1,

t e s t 3 a (NewN ) .

I The following is not tail recursive (it has alternatives forpredicates in the recursive clause preceding the recursive call,so backtracking may be necessary):

t e s t 4 (N):− w r i t e (N) , n l , m(N, NewN) ,t e s t 4 (NewN ) .

m(N, NewN):− N >= 0 , NewN i s N + 1 .m(N, NewN):− N < 0 , NewN i s (−1)*N.

Making recursive predicates tail recursive

I If a predicate is not tail recursive because it has backtrackingpoints, then it can be made so by using the cut before therecursive call.

I The following are now tail recursive:

t e s t 5 (N):− w r i t e (N) , n l , NewN i s N+1 ,! ,t e s t 5 (NewN ) .

t e s t 5 (N):− N<0.t e s t 6 (N):− w r i t e (N) , n l , m(N, NewN) , ! ,

t e s t 6 (NewN ) .m(N, NewN):− N >= 0 , NewN i s N + 1 .m(N, NewN):− N < 0 , NewN i s (−1)*N.

Making recursive predicates tail recursive

I If a predicate is not tail recursive because it has backtrackingpoints, then it can be made so by using the cut before therecursive call.

I The following are now tail recursive:

t e s t 5 (N):− w r i t e (N) , n l , NewN i s N+1 ,! ,t e s t 5 (NewN ) .

t e s t 5 (N):− N<0.t e s t 6 (N):− w r i t e (N) , n l , m(N, NewN) , ! ,

t e s t 6 (NewN ) .m(N, NewN):− N >= 0 , NewN i s N + 1 .m(N, NewN):− N < 0 , NewN i s (−1)*N.

I Note that tail recursion can be indirect. The following is tailrecursive:

t e s t 7 (N):− w r i t e (N) , n l , t e s t 7 a (N ) .t e s t 7 a (N):− NewN i s N+1, t e s t 7 (NewN ) .

In the above we have mutual recursion, but note that test7ais just used to rename part of the test7 predicate.

Summary: tail recursion

I In Prolog, tail recursion exists when:I the recursive call is the last subgoal in the clause,I there are no untried alternative clauses,I there are no untried alternatives for any subgoal preceding the

recursive call in the same clause.

I Consider the program:

a ( b ) .a ( c ) .

d ( e ) .d ( f ) .

and the query ?−d(f).

I Contrary to the expectation, most Prolog implementationswill not have to go through all the knowledge base.

I Prolog uses indexing over the functor name and the firstargument.

I These indices will be stored as a hash table or somethingsimilar for fast access.

I Therefore, Prolog will find d(f) directly.

I Consider the program:

a ( b ) .a ( c ) .

d ( e ) .d ( f ) .

and the query ?−d(f).

I Contrary to the expectation, most Prolog implementationswill not have to go through all the knowledge base.

I Prolog uses indexing over the functor name and the firstargument.

I These indices will be stored as a hash table or somethingsimilar for fast access.

I Therefore, Prolog will find d(f) directly.

I Consider the program:

a ( b ) .a ( c ) .

d ( e ) .d ( f ) .

and the query ?−d(f).

I Contrary to the expectation, most Prolog implementationswill not have to go through all the knowledge base.

I Prolog uses indexing over the functor name and the firstargument.

I These indices will be stored as a hash table or somethingsimilar for fast access.

I Therefore, Prolog will find d(f) directly.

I Consider the program:

a ( b ) .a ( c ) .

d ( e ) .d ( f ) .

and the query ?−d(f).

I Contrary to the expectation, most Prolog implementationswill not have to go through all the knowledge base.

I Prolog uses indexing over the functor name and the firstargument.

I These indices will be stored as a hash table or somethingsimilar for fast access.

I Therefore, Prolog will find d(f) directly.

I Consider the program:

a ( b ) .a ( c ) .

d ( e ) .d ( f ) .

and the query ?−d(f).

I Contrary to the expectation, most Prolog implementationswill not have to go through all the knowledge base.

I Prolog uses indexing over the functor name and the firstargument.

I These indices will be stored as a hash table or somethingsimilar for fast access.

I Therefore, Prolog will find d(f) directly.

I Using indexing can make predicates be tail recursive whenthey would not be:

t e s t 8 (0):− w r i t e ( ’ S t i l l go ing ’ ) , n l , t e s t 8 ( 0 ) .t e s t 8 (−1).

The second clause is not an alternative to the first because ofindexing.

I Note, however, that indexing works only when the firstargument of the predicate is instantiated.

I Using indexing can make predicates be tail recursive whenthey would not be:

t e s t 8 (0):− w r i t e ( ’ S t i l l go ing ’ ) , n l , t e s t 8 ( 0 ) .t e s t 8 (−1).

The second clause is not an alternative to the first because ofindexing.

I Note, however, that indexing works only when the firstargument of the predicate is instantiated.

I Consider some built-in predicates in Prolog, as presented inthe help section of the program:

append (? L i s t 1 , ? L i s t 2 , ? L i s t 3 )

Succeeds when List3 unifies with the concatenation of List1 and List2.

The predicate can be used with any instantiation pattern (even three

variables).

−Number i s +Expr [ ISO ]

True if Number has successfully been unified with the number Expr

evaluates to. If Expr evaluates to a float that can be represented using an

integer (i.e, the value is integer and within the range that can be

described by Prolog’s integer representation), Expr is unified with the

integer value.

I The above examples use a notation (documentation)convention in Prolog: when describing the predicate, usemode indicators for its arguments:

+ describes an argument that should already be instantiatedwhen the predicate is called,

- denotes an argument that is normally not instantiated untilthis predicate instantiates it,

? denotes an argument that may or may not be instantiated,@ is used by some programmers to indicate that the argument

contains variables that must not be instantiated.

Note that the above description does not ensure guaranteewhat would happen if the argument is used in another mode.For that matter, it does not even guarantee the intendedbehavior.

I The above examples use a notation (documentation)convention in Prolog: when describing the predicate, usemode indicators for its arguments:

+ describes an argument that should already be instantiatedwhen the predicate is called,

- denotes an argument that is normally not instantiated untilthis predicate instantiates it,

? denotes an argument that may or may not be instantiated,@ is used by some programmers to indicate that the argument

contains variables that must not be instantiated.

Note that the above description does not ensure guaranteewhat would happen if the argument is used in another mode.For that matter, it does not even guarantee the intendedbehavior.

I The above examples use a notation (documentation)convention in Prolog: when describing the predicate, usemode indicators for its arguments:

+ describes an argument that should already be instantiatedwhen the predicate is called,

- denotes an argument that is normally not instantiated untilthis predicate instantiates it,

? denotes an argument that may or may not be instantiated,@ is used by some programmers to indicate that the argument

contains variables that must not be instantiated.

Note that the above description does not ensure guaranteewhat would happen if the argument is used in another mode.For that matter, it does not even guarantee the intendedbehavior.

I The above examples use a notation (documentation)convention in Prolog: when describing the predicate, usemode indicators for its arguments:

+ describes an argument that should already be instantiatedwhen the predicate is called,

- denotes an argument that is normally not instantiated untilthis predicate instantiates it,

? denotes an argument that may or may not be instantiated,

@ is used by some programmers to indicate that the argumentcontains variables that must not be instantiated.

Note that the above description does not ensure guaranteewhat would happen if the argument is used in another mode.For that matter, it does not even guarantee the intendedbehavior.

I The above examples use a notation (documentation)convention in Prolog: when describing the predicate, usemode indicators for its arguments:

+ describes an argument that should already be instantiatedwhen the predicate is called,

- denotes an argument that is normally not instantiated untilthis predicate instantiates it,

? denotes an argument that may or may not be instantiated,@ is used by some programmers to indicate that the argument

contains variables that must not be instantiated.

Note that the above description does not ensure guaranteewhat would happen if the argument is used in another mode.For that matter, it does not even guarantee the intendedbehavior.

I There are two styles of I/O in Prolog:I Edinburg style I/O is the legacy style, still supported by Prolog

implementations. It is relatively simple to use but has somelimitations.

I ISO I/O is the standard style, supported by all Prologimplementations.

I There are some overlaps between the two styles.

Writing termsI The built-in predicate write takes any Prolog term and

displays it on the screen.

I The predicate nl moves the “cursor” at a new line.

? − w r i t e ( ’ H e l l o t h e r e ’ ) , n l , w r i t e ( ’ Goodbye ’ ) .H e l l o t h e r eGoodbyet r u e .

I Note that quoted atoms are displayed without quotes. Thevariant writeq of write will also display the quotes.

?− w r i t e (X ) .G243t r u e .

?− w r i t e (” some s t r ” ) .[ 1 1 5 , 111 , 109 , 101 , 32 , 115 , 116 , 1 1 4 ]t r u e .

II Note that Prolog displays the internal representation of terms.In particular, the internal representation of variables.

Writing termsI The built-in predicate write takes any Prolog term and

displays it on the screen.I The predicate nl moves the “cursor” at a new line.

? − w r i t e ( ’ H e l l o t h e r e ’ ) , n l , w r i t e ( ’ Goodbye ’ ) .H e l l o t h e r eGoodbyet r u e .

I Note that quoted atoms are displayed without quotes. Thevariant writeq of write will also display the quotes.

?− w r i t e (X ) .G243t r u e .

?− w r i t e (” some s t r ” ) .[ 1 1 5 , 111 , 109 , 101 , 32 , 115 , 116 , 1 1 4 ]t r u e .

II Note that Prolog displays the internal representation of terms.In particular, the internal representation of variables.

Writing termsI The built-in predicate write takes any Prolog term and

displays it on the screen.I The predicate nl moves the “cursor” at a new line.

? − w r i t e ( ’ H e l l o t h e r e ’ ) , n l , w r i t e ( ’ Goodbye ’ ) .H e l l o t h e r eGoodbyet r u e .

I Note that quoted atoms are displayed without quotes. Thevariant writeq of write will also display the quotes.

?− w r i t e (X ) .G243t r u e .

?− w r i t e (” some s t r ” ) .[ 1 1 5 , 111 , 109 , 101 , 32 , 115 , 116 , 1 1 4 ]t r u e .

II Note that Prolog displays the internal representation of terms.In particular, the internal representation of variables.

Writing termsI The built-in predicate write takes any Prolog term and

displays it on the screen.I The predicate nl moves the “cursor” at a new line.

? − w r i t e ( ’ H e l l o t h e r e ’ ) , n l , w r i t e ( ’ Goodbye ’ ) .H e l l o t h e r eGoodbyet r u e .

I Note that quoted atoms are displayed without quotes. Thevariant writeq of write will also display the quotes.

?− w r i t e (X ) .G243t r u e .

?− w r i t e (” some s t r ” ) .[ 1 1 5 , 111 , 109 , 101 , 32 , 115 , 116 , 1 1 4 ]t r u e .

II Note that Prolog displays the internal representation of terms.In particular, the internal representation of variables.

Writing termsI The built-in predicate write takes any Prolog term and

displays it on the screen.I The predicate nl moves the “cursor” at a new line.

? − w r i t e ( ’ H e l l o t h e r e ’ ) , n l , w r i t e ( ’ Goodbye ’ ) .H e l l o t h e r eGoodbyet r u e .

I Note that quoted atoms are displayed without quotes. Thevariant writeq of write will also display the quotes.

?− w r i t e (X ) .G243t r u e .

?− w r i t e (” some s t r ” ) .[ 1 1 5 , 111 , 109 , 101 , 32 , 115 , 116 , 1 1 4 ]t r u e .

II Note that Prolog displays the internal representation of terms.In particular, the internal representation of variables.

Writing termsI The built-in predicate write takes any Prolog term and

displays it on the screen.I The predicate nl moves the “cursor” at a new line.

? − w r i t e ( ’ H e l l o t h e r e ’ ) , n l , w r i t e ( ’ Goodbye ’ ) .H e l l o t h e r eGoodbyet r u e .

I Note that quoted atoms are displayed without quotes. Thevariant writeq of write will also display the quotes.

?− w r i t e (X ) .G243t r u e .

?− w r i t e (” some s t r ” ) .[ 1 1 5 , 111 , 109 , 101 , 32 , 115 , 116 , 1 1 4 ]t r u e .

II Note that Prolog displays the internal representation of terms.In particular, the internal representation of variables.

Reading terms

I The predicate read accepts any Prolog term from thekeyboard (typed in Prolog syntax, followed by the period).

?− r e a d (X ) .| : h e l l o .

X = h e l l o .

?− r e a d (X ) .| : ’ h e l l o t h e r e ’ .

X = ’ h e l l o t h e r e ’ .

?− r e a d (X ) .| : h e l l o t h e r e .

ERROR: Stream u s e r i n p u t : 0 : 3 7Syntax e r r o r : O p er a t or e x p e c t e d

?− r e a d ( h e l l o ) .| : h e l l o .t r u e .

?− r e a d ( h e l l o ) .| : bye .f a l s e .

?− r e a d (X ) .| : mother (Y, ada ) .

X = mother ( G288 , ada ) .

I The read predicate succeeds if its argument can be unifiedwith the term given by the user (if this is a term). Theexamples above illustrate several possible uses and situations.

File handling

I The predicate see takes a file as argument, the effect is toopen the file for reading such that Prolog gets input from thatfile rather than the console.

I The predicate seen closes all open files, input now comesagain from the console.

? − s e e ( ’ m y f i l e . t x t ’ ) ,r e a d (X) ,r e a d (Y) ,r e a d (Z ) ,s e e n .

I When a file is opened, Prolog will keep track of the positionof the “cursor” in that file.

File handling

I The predicate see takes a file as argument, the effect is toopen the file for reading such that Prolog gets input from thatfile rather than the console.

I The predicate seen closes all open files, input now comesagain from the console.

? − s e e ( ’ m y f i l e . t x t ’ ) ,r e a d (X) ,r e a d (Y) ,r e a d (Z ) ,s e e n .

I When a file is opened, Prolog will keep track of the positionof the “cursor” in that file.

File handling

I The predicate see takes a file as argument, the effect is toopen the file for reading such that Prolog gets input from thatfile rather than the console.

I The predicate seen closes all open files, input now comesagain from the console.

? − s e e ( ’ m y f i l e . t x t ’ ) ,r e a d (X) ,r e a d (Y) ,r e a d (Z ) ,s e e n .

I When a file is opened, Prolog will keep track of the positionof the “cursor” in that file.

File handling

I The predicate see takes a file as argument, the effect is toopen the file for reading such that Prolog gets input from thatfile rather than the console.

I The predicate seen closes all open files, input now comesagain from the console.

? − s e e ( ’ m y f i l e . t x t ’ ) ,r e a d (X) ,r e a d (Y) ,r e a d (Z ) ,s e e n .

I When a file is opened, Prolog will keep track of the positionof the “cursor” in that file.

I One can switch between several open files:

?− s e e ( ’ aaaa ’ ) ,r e a d (X1 ) ,s e e ( ’ bbbb ’ ) ,r e a d (X2 ) ,s e e ( ’ cccc ’ ) ,r e a d (X3 ) ,s e e n .

I The predicate tell opens a file for writing and switches theoutput to it.

I The predicate told closes all files opened for writing andreturns the output to being the console.

? − t e l l ( ’ m y f i l e . t x t ’ ) ,w r i t e ( ’ H e l l o t h e r e ’ ) ,n l ,t o l d .

I Several files can be opened and written into:

?− t e l l ( ’ aaaa ’ ) ,w r i t e ( ’ f i r s t l i n e o f aaaa ’ ) , n l ,t e l l ( ’ bbbb ’ ) ,w r i t e ( ’ f i r s t l i n e o f bbbb ’ ) , n l ,t e l l ( ’ cccc ’ ) ,w r i t e ( ’ f i r s t l i n e o f cccc ’ ) , n l ,t o l d .

I The predicate tell opens a file for writing and switches theoutput to it.

I The predicate told closes all files opened for writing andreturns the output to being the console.

? − t e l l ( ’ m y f i l e . t x t ’ ) ,w r i t e ( ’ H e l l o t h e r e ’ ) ,n l ,t o l d .

I Several files can be opened and written into:

?− t e l l ( ’ aaaa ’ ) ,w r i t e ( ’ f i r s t l i n e o f aaaa ’ ) , n l ,t e l l ( ’ bbbb ’ ) ,w r i t e ( ’ f i r s t l i n e o f bbbb ’ ) , n l ,t e l l ( ’ cccc ’ ) ,w r i t e ( ’ f i r s t l i n e o f cccc ’ ) , n l ,t o l d .

I The predicate tell opens a file for writing and switches theoutput to it.

I The predicate told closes all files opened for writing andreturns the output to being the console.

? − t e l l ( ’ m y f i l e . t x t ’ ) ,w r i t e ( ’ H e l l o t h e r e ’ ) ,n l ,t o l d .

I Several files can be opened and written into:

?− t e l l ( ’ aaaa ’ ) ,w r i t e ( ’ f i r s t l i n e o f aaaa ’ ) , n l ,t e l l ( ’ bbbb ’ ) ,w r i t e ( ’ f i r s t l i n e o f bbbb ’ ) , n l ,t e l l ( ’ cccc ’ ) ,w r i t e ( ’ f i r s t l i n e o f cccc ’ ) , n l ,t o l d .

Character level I/OI The predicate put writes one character (integer representing

the ASCII code corresponding to the character).

?− put ( 4 2 ) .*

t r u e .

I The predicate get reads one character from the default input(console).

?− g e t (X ) .| %

X = 3 7 .

I In SWI Prolog, put can also handle nonprinting characters:

?− w r i t e ( h e l l o ) , put ( 8 ) , w r i t e ( bye ) .h e l l b y et r u e .

Character level I/OI The predicate put writes one character (integer representing

the ASCII code corresponding to the character).

?− put ( 4 2 ) .*

t r u e .

I The predicate get reads one character from the default input(console).

?− g e t (X ) .| %

X = 3 7 .

I In SWI Prolog, put can also handle nonprinting characters:

?− w r i t e ( h e l l o ) , put ( 8 ) , w r i t e ( bye ) .h e l l b y et r u e .

Character level I/OI The predicate put writes one character (integer representing

the ASCII code corresponding to the character).

?− put ( 4 2 ) .*

t r u e .

I The predicate get reads one character from the default input(console).

?− g e t (X ) .| %

X = 3 7 .

I In SWI Prolog, put can also handle nonprinting characters:

?− w r i t e ( h e l l o ) , put ( 8 ) , w r i t e ( bye ) .h e l l b y et r u e .

Complete Information: SWI-Prolog Manual

I For exact details of the Edinburgh style I/O predicates in SWIProlog, consult [Wielemaker, 2008] (also available in SWIProlog by calling ? − help.).

Streams

I ISO standard I/O in Prolog considers the notion of a stream(open files or file-like objects).

I ISO I/O predicates are provided for:

I Open and close streams in different modes.I Inspecting the status of a stream, as well as other information.I Reading/writing is done in streams.

I There are two special streams that are always open:user input and user output.

Streams

I ISO standard I/O in Prolog considers the notion of a stream(open files or file-like objects).

I ISO I/O predicates are provided for:

I Open and close streams in different modes.I Inspecting the status of a stream, as well as other information.I Reading/writing is done in streams.

I There are two special streams that are always open:user input and user output.

Streams

I ISO standard I/O in Prolog considers the notion of a stream(open files or file-like objects).

I ISO I/O predicates are provided for:I Open and close streams in different modes.

I Inspecting the status of a stream, as well as other information.I Reading/writing is done in streams.

I There are two special streams that are always open:user input and user output.

Streams

I ISO standard I/O in Prolog considers the notion of a stream(open files or file-like objects).

I ISO I/O predicates are provided for:I Open and close streams in different modes.I Inspecting the status of a stream, as well as other information.

I Reading/writing is done in streams.

I There are two special streams that are always open:user input and user output.

Streams

I ISO standard I/O in Prolog considers the notion of a stream(open files or file-like objects).

I ISO I/O predicates are provided for:I Open and close streams in different modes.I Inspecting the status of a stream, as well as other information.I Reading/writing is done in streams.

I There are two special streams that are always open:user input and user output.

Streams

I ISO standard I/O in Prolog considers the notion of a stream(open files or file-like objects).

I ISO I/O predicates are provided for:I Open and close streams in different modes.I Inspecting the status of a stream, as well as other information.I Reading/writing is done in streams.

I There are two special streams that are always open:user input and user output.

Opening streams

I The predicate open(Filename, Mode, Stream, Options) opensa stream, where:

Filename indicates the file name (implementation, OSdependent),Mode is one of read, write, append,Stream is a “handle” for the file,Options is a (possibly empty) list of options. Options include:

I type(text) (default) or type(binary),I reposition (true) or reposition ( false ) (the default) –

indicating whether it is possible to skip back or forward tospecified positions,

I alias (Atom) – a name (atom) for the stream,I action for reading past the end of the line: eof action ( error )

- raise an error condition, oef action (eof code) - return anerror code, eof action ( reset ) - to examine the file again (incase it was updated e.g. by another concurrent process).

Opening streams

I The predicate open(Filename, Mode, Stream, Options) opensa stream, where:

Filename indicates the file name (implementation, OSdependent),

Mode is one of read, write, append,Stream is a “handle” for the file,Options is a (possibly empty) list of options. Options include:

I type(text) (default) or type(binary),I reposition (true) or reposition ( false ) (the default) –

indicating whether it is possible to skip back or forward tospecified positions,

I alias (Atom) – a name (atom) for the stream,I action for reading past the end of the line: eof action ( error )

- raise an error condition, oef action (eof code) - return anerror code, eof action ( reset ) - to examine the file again (incase it was updated e.g. by another concurrent process).

Opening streams

I The predicate open(Filename, Mode, Stream, Options) opensa stream, where:

Filename indicates the file name (implementation, OSdependent),Mode is one of read, write, append,

Stream is a “handle” for the file,Options is a (possibly empty) list of options. Options include:

I type(text) (default) or type(binary),I reposition (true) or reposition ( false ) (the default) –

indicating whether it is possible to skip back or forward tospecified positions,

I alias (Atom) – a name (atom) for the stream,I action for reading past the end of the line: eof action ( error )

- raise an error condition, oef action (eof code) - return anerror code, eof action ( reset ) - to examine the file again (incase it was updated e.g. by another concurrent process).

Opening streams

I The predicate open(Filename, Mode, Stream, Options) opensa stream, where:

Filename indicates the file name (implementation, OSdependent),Mode is one of read, write, append,Stream is a “handle” for the file,

Options is a (possibly empty) list of options. Options include:

I type(text) (default) or type(binary),I reposition (true) or reposition ( false ) (the default) –

indicating whether it is possible to skip back or forward tospecified positions,

I alias (Atom) – a name (atom) for the stream,I action for reading past the end of the line: eof action ( error )

- raise an error condition, oef action (eof code) - return anerror code, eof action ( reset ) - to examine the file again (incase it was updated e.g. by another concurrent process).

Opening streams

I The predicate open(Filename, Mode, Stream, Options) opensa stream, where:

Filename indicates the file name (implementation, OSdependent),Mode is one of read, write, append,Stream is a “handle” for the file,Options is a (possibly empty) list of options. Options include:

I type(text) (default) or type(binary),I reposition (true) or reposition ( false ) (the default) –

indicating whether it is possible to skip back or forward tospecified positions,

I alias (Atom) – a name (atom) for the stream,I action for reading past the end of the line: eof action ( error )

- raise an error condition, oef action (eof code) - return anerror code, eof action ( reset ) - to examine the file again (incase it was updated e.g. by another concurrent process).

Opening streams

I The predicate open(Filename, Mode, Stream, Options) opensa stream, where:

Filename indicates the file name (implementation, OSdependent),Mode is one of read, write, append,Stream is a “handle” for the file,Options is a (possibly empty) list of options. Options include:

I type(text) (default) or type(binary),

I reposition (true) or reposition ( false ) (the default) –indicating whether it is possible to skip back or forward tospecified positions,

I alias (Atom) – a name (atom) for the stream,I action for reading past the end of the line: eof action ( error )

- raise an error condition, oef action (eof code) - return anerror code, eof action ( reset ) - to examine the file again (incase it was updated e.g. by another concurrent process).

Opening streams

I The predicate open(Filename, Mode, Stream, Options) opensa stream, where:

Filename indicates the file name (implementation, OSdependent),Mode is one of read, write, append,Stream is a “handle” for the file,Options is a (possibly empty) list of options. Options include:

I type(text) (default) or type(binary),I reposition (true) or reposition ( false ) (the default) –

indicating whether it is possible to skip back or forward tospecified positions,

I alias (Atom) – a name (atom) for the stream,I action for reading past the end of the line: eof action ( error )

- raise an error condition, oef action (eof code) - return anerror code, eof action ( reset ) - to examine the file again (incase it was updated e.g. by another concurrent process).

Opening streams

I The predicate open(Filename, Mode, Stream, Options) opensa stream, where:

Filename indicates the file name (implementation, OSdependent),Mode is one of read, write, append,Stream is a “handle” for the file,Options is a (possibly empty) list of options. Options include:

I type(text) (default) or type(binary),I reposition (true) or reposition ( false ) (the default) –

indicating whether it is possible to skip back or forward tospecified positions,

I alias (Atom) – a name (atom) for the stream,

I action for reading past the end of the line: eof action ( error )- raise an error condition, oef action (eof code) - return anerror code, eof action ( reset ) - to examine the file again (incase it was updated e.g. by another concurrent process).

Opening streams

I The predicate open(Filename, Mode, Stream, Options) opensa stream, where:

Filename indicates the file name (implementation, OSdependent),Mode is one of read, write, append,Stream is a “handle” for the file,Options is a (possibly empty) list of options. Options include:

I type(text) (default) or type(binary),I reposition (true) or reposition ( false ) (the default) –

indicating whether it is possible to skip back or forward tospecified positions,

I alias (Atom) – a name (atom) for the stream,I action for reading past the end of the line: eof action ( error )

- raise an error condition, oef action (eof code) - return anerror code, eof action ( reset ) - to examine the file again (incase it was updated e.g. by another concurrent process).

I Example:

t e s t :−open ( ’ f i l e . t x t ’ , read , MyStream , [ t y p e ( t e x t ) ] ) ,r e a d t e r m ( MyStream , Term , [ quoted ( t r u e ) ] ) ,c l o s e ( MyStream ) , w r i t e ( Term ) .

Closing streams

I The predicate close (Stream, Options) closes Stream withOptions.

I close (Stream) is the version without options.

I Options include force ( false ) (default) and force (true) -even if there is an error (e.g. the file was on a removablestorage device which was removed), the file is consideredclosed, without raising an error.

Closing streams

I The predicate close (Stream, Options) closes Stream withOptions.

I close (Stream) is the version without options.

I Options include force ( false ) (default) and force (true) -even if there is an error (e.g. the file was on a removablestorage device which was removed), the file is consideredclosed, without raising an error.

Closing streams

I The predicate close (Stream, Options) closes Stream withOptions.

I close (Stream) is the version without options.

I Options include force ( false ) (default) and force (true) -even if there is an error (e.g. the file was on a removablestorage device which was removed), the file is consideredclosed, without raising an error.

Stream properties

I The predicate stream property(Stream, Property) can beused to get properties like:

I file name (...) ,I mode(M),I alias (A),I etc, consult the documentation [Wielemaker, 2008] for the rest

of the options.

I Example:

?− s t r e a m p r o p e r t y ( u s e r i n p u t , mode ( What ) ) .What = r e a d .

Stream properties

I The predicate stream property(Stream, Property) can beused to get properties like:

I file name (...) ,

I mode(M),I alias (A),I etc, consult the documentation [Wielemaker, 2008] for the rest

of the options.

I Example:

?− s t r e a m p r o p e r t y ( u s e r i n p u t , mode ( What ) ) .What = r e a d .

Stream properties

I The predicate stream property(Stream, Property) can beused to get properties like:

I file name (...) ,I mode(M),

I alias (A),I etc, consult the documentation [Wielemaker, 2008] for the rest

of the options.

I Example:

?− s t r e a m p r o p e r t y ( u s e r i n p u t , mode ( What ) ) .What = r e a d .

Stream properties

I The predicate stream property(Stream, Property) can beused to get properties like:

I file name (...) ,I mode(M),I alias (A),

I etc, consult the documentation [Wielemaker, 2008] for the restof the options.

I Example:

?− s t r e a m p r o p e r t y ( u s e r i n p u t , mode ( What ) ) .What = r e a d .

Stream properties

I The predicate stream property(Stream, Property) can beused to get properties like:

I file name (...) ,I mode(M),I alias (A),I etc, consult the documentation [Wielemaker, 2008] for the rest

of the options.

I Example:

?− s t r e a m p r o p e r t y ( u s e r i n p u t , mode ( What ) ) .What = r e a d .

Stream properties

I The predicate stream property(Stream, Property) can beused to get properties like:

I file name (...) ,I mode(M),I alias (A),I etc, consult the documentation [Wielemaker, 2008] for the rest

of the options.

I Example:

?− s t r e a m p r o p e r t y ( u s e r i n p u t , mode ( What ) ) .What = r e a d .

Reading terms

I Predicates for reading terms:

read term(Stream, Term, Options),read term(Term, Options), using the current input stream,read(Stream, Term) like the above, without the options,read(Term) like the above, from current input.

I Read about the Options in thedocumentation [Wielemaker, 2008].

I The following example illustrates the use ofvariable names, variables , singletons :

?− r e a d t e r m ( Term , [ v a r i a b l e n a m e s ( Vars ) ,s i n g l e t o n s ( S ) , v a r i a b l e s ( L i s t ) ] ) .| f (X, X, Y, Z ) .Term = f ( G359 , G359 , G361 , G362 ) ,Vars = [ ’ X’= G359 , ’Y’= G361 , ’Z’= G362 ] ,S = [ ’ Y’= G361 , ’Z’= G362 ] ,L i s t = [ G359 , G361 , G362 ] .

Reading terms

I Predicates for reading terms:

read term(Stream, Term, Options),

read term(Term, Options), using the current input stream,read(Stream, Term) like the above, without the options,read(Term) like the above, from current input.

I Read about the Options in thedocumentation [Wielemaker, 2008].

I The following example illustrates the use ofvariable names, variables , singletons :

?− r e a d t e r m ( Term , [ v a r i a b l e n a m e s ( Vars ) ,s i n g l e t o n s ( S ) , v a r i a b l e s ( L i s t ) ] ) .| f (X, X, Y, Z ) .Term = f ( G359 , G359 , G361 , G362 ) ,Vars = [ ’ X’= G359 , ’Y’= G361 , ’Z’= G362 ] ,S = [ ’ Y’= G361 , ’Z’= G362 ] ,L i s t = [ G359 , G361 , G362 ] .

Reading terms

I Predicates for reading terms:

read term(Stream, Term, Options),read term(Term, Options), using the current input stream,

read(Stream, Term) like the above, without the options,read(Term) like the above, from current input.

I Read about the Options in thedocumentation [Wielemaker, 2008].

I The following example illustrates the use ofvariable names, variables , singletons :

?− r e a d t e r m ( Term , [ v a r i a b l e n a m e s ( Vars ) ,s i n g l e t o n s ( S ) , v a r i a b l e s ( L i s t ) ] ) .| f (X, X, Y, Z ) .Term = f ( G359 , G359 , G361 , G362 ) ,Vars = [ ’ X’= G359 , ’Y’= G361 , ’Z’= G362 ] ,S = [ ’ Y’= G361 , ’Z’= G362 ] ,L i s t = [ G359 , G361 , G362 ] .

Reading terms

I Predicates for reading terms:

read term(Stream, Term, Options),read term(Term, Options), using the current input stream,read(Stream, Term) like the above, without the options,

read(Term) like the above, from current input.

I Read about the Options in thedocumentation [Wielemaker, 2008].

I The following example illustrates the use ofvariable names, variables , singletons :

?− r e a d t e r m ( Term , [ v a r i a b l e n a m e s ( Vars ) ,s i n g l e t o n s ( S ) , v a r i a b l e s ( L i s t ) ] ) .| f (X, X, Y, Z ) .Term = f ( G359 , G359 , G361 , G362 ) ,Vars = [ ’ X’= G359 , ’Y’= G361 , ’Z’= G362 ] ,S = [ ’ Y’= G361 , ’Z’= G362 ] ,L i s t = [ G359 , G361 , G362 ] .

Reading terms

I Predicates for reading terms:

read term(Stream, Term, Options),read term(Term, Options), using the current input stream,read(Stream, Term) like the above, without the options,read(Term) like the above, from current input.

I Read about the Options in thedocumentation [Wielemaker, 2008].

I The following example illustrates the use ofvariable names, variables , singletons :

?− r e a d t e r m ( Term , [ v a r i a b l e n a m e s ( Vars ) ,s i n g l e t o n s ( S ) , v a r i a b l e s ( L i s t ) ] ) .| f (X, X, Y, Z ) .Term = f ( G359 , G359 , G361 , G362 ) ,Vars = [ ’ X’= G359 , ’Y’= G361 , ’Z’= G362 ] ,S = [ ’ Y’= G361 , ’Z’= G362 ] ,L i s t = [ G359 , G361 , G362 ] .

Reading terms

I Predicates for reading terms:

read term(Stream, Term, Options),read term(Term, Options), using the current input stream,read(Stream, Term) like the above, without the options,read(Term) like the above, from current input.

I Read about the Options in thedocumentation [Wielemaker, 2008].

I The following example illustrates the use ofvariable names, variables , singletons :

?− r e a d t e r m ( Term , [ v a r i a b l e n a m e s ( Vars ) ,s i n g l e t o n s ( S ) , v a r i a b l e s ( L i s t ) ] ) .| f (X, X, Y, Z ) .Term = f ( G359 , G359 , G361 , G362 ) ,Vars = [ ’ X’= G359 , ’Y’= G361 , ’Z’= G362 ] ,S = [ ’ Y’= G361 , ’Z’= G362 ] ,L i s t = [ G359 , G361 , G362 ] .

Reading terms

I Predicates for reading terms:

read term(Stream, Term, Options),read term(Term, Options), using the current input stream,read(Stream, Term) like the above, without the options,read(Term) like the above, from current input.

I Read about the Options in thedocumentation [Wielemaker, 2008].

I The following example illustrates the use ofvariable names, variables , singletons :

?− r e a d t e r m ( Term , [ v a r i a b l e n a m e s ( Vars ) ,s i n g l e t o n s ( S ) , v a r i a b l e s ( L i s t ) ] ) .| f (X, X, Y, Z ) .Term = f ( G359 , G359 , G361 , G362 ) ,Vars = [ ’ X’= G359 , ’Y’= G361 , ’Z’= G362 ] ,S = [ ’ Y’= G361 , ’Z’= G362 ] ,L i s t = [ G359 , G361 , G362 ] .

Writing terms

I Predicates for writing terms include:

write term(Stream, Term, Options),write term(Term, Options),write (Stream, Term),write (Term),

the variants being analogous to the ones for reading terms.

I For options, other predicates for writing terms, consult thedocumentation.

Writing terms

I Predicates for writing terms include:

write term(Stream, Term, Options),

write term(Term, Options),write (Stream, Term),write (Term),

the variants being analogous to the ones for reading terms.

I For options, other predicates for writing terms, consult thedocumentation.

Writing terms

I Predicates for writing terms include:

write term(Stream, Term, Options),write term(Term, Options),

write (Stream, Term),write (Term),

the variants being analogous to the ones for reading terms.

I For options, other predicates for writing terms, consult thedocumentation.

Writing terms

I Predicates for writing terms include:

write term(Stream, Term, Options),write term(Term, Options),write (Stream, Term),

write (Term),

the variants being analogous to the ones for reading terms.

I For options, other predicates for writing terms, consult thedocumentation.

Writing terms

I Predicates for writing terms include:

write term(Stream, Term, Options),write term(Term, Options),write (Stream, Term),write (Term),

the variants being analogous to the ones for reading terms.

I For options, other predicates for writing terms, consult thedocumentation.

Writing terms

I Predicates for writing terms include:

write term(Stream, Term, Options),write term(Term, Options),write (Stream, Term),write (Term),

the variants being analogous to the ones for reading terms.

I For options, other predicates for writing terms, consult thedocumentation.

Writing terms

I Predicates for writing terms include:

write term(Stream, Term, Options),write term(Term, Options),write (Stream, Term),write (Term),

the variants being analogous to the ones for reading terms.

I For options, other predicates for writing terms, consult thedocumentation.

Other I/O predicates

I Other I/O predicates include predicates for reading/writingcharacters/bytes:

I get char, peek char, put char, put code, get code, peek code,get byte, peek byte, put byte.

I Other predicates:

I current input , current output, set input , set output,flush output , at the end of stream , nl, etc.

I Consult the documentation for the details of the syntax.

Other I/O predicates

I Other I/O predicates include predicates for reading/writingcharacters/bytes:

I get char, peek char, put char, put code, get code, peek code,get byte, peek byte, put byte.

I Other predicates:

I current input , current output, set input , set output,flush output , at the end of stream , nl, etc.

I Consult the documentation for the details of the syntax.

Other I/O predicates

I Other I/O predicates include predicates for reading/writingcharacters/bytes:

I get char, peek char, put char, put code, get code, peek code,get byte, peek byte, put byte.

I Other predicates:

I current input , current output, set input , set output,flush output , at the end of stream , nl, etc.

I Consult the documentation for the details of the syntax.

Other I/O predicates

I Other I/O predicates include predicates for reading/writingcharacters/bytes:

I get char, peek char, put char, put code, get code, peek code,get byte, peek byte, put byte.

I Other predicates:I current input , current output, set input , set output,

flush output , at the end of stream , nl, etc.

I Consult the documentation for the details of the syntax.

Other I/O predicates

I Other I/O predicates include predicates for reading/writingcharacters/bytes:

I get char, peek char, put char, put code, get code, peek code,get byte, peek byte, put byte.

I Other predicates:I current input , current output, set input , set output,

flush output , at the end of stream , nl, etc.

I Consult the documentation for the details of the syntax.

Operators in PrologI The usual way to write a Prolog predicate is to put it in front

of its arguments:

f u n c t o r ( arg1 , arg2 , . . . )

I However, there are situations where having a different positioncan make the programs easier to understand:

X i s f a t h e r o f Y

I In Prolog, one can define new operators by specifying:

I the position: whether the operator is prefix (default), infix orpostfix,

I the precedence: to decide which operator applies first (e.g. is2+3*4 (2+3)*4 or 2+(3*4)?), lower precedence binds thestrongest, precedences are between 1 and 1200,

I the associativity: e.g. is 8/2/2 (8/2)/2 or is it 8/(2/2)?I Note that logic predicates (i.e. those expressions that evaluate

to “true” or “false” are not associative in general). Consider:3 = 4 = 3, and suppose it were left associative, then (3 = 4)= 3 evaluates to “false” = 3, which changes the type of thearguments.

Operators in PrologI The usual way to write a Prolog predicate is to put it in front

of its arguments:

f u n c t o r ( arg1 , arg2 , . . . )

I However, there are situations where having a different positioncan make the programs easier to understand:

X i s f a t h e r o f Y

I In Prolog, one can define new operators by specifying:

I the position: whether the operator is prefix (default), infix orpostfix,

I the precedence: to decide which operator applies first (e.g. is2+3*4 (2+3)*4 or 2+(3*4)?), lower precedence binds thestrongest, precedences are between 1 and 1200,

I the associativity: e.g. is 8/2/2 (8/2)/2 or is it 8/(2/2)?I Note that logic predicates (i.e. those expressions that evaluate

to “true” or “false” are not associative in general). Consider:3 = 4 = 3, and suppose it were left associative, then (3 = 4)= 3 evaluates to “false” = 3, which changes the type of thearguments.

Operators in PrologI The usual way to write a Prolog predicate is to put it in front

of its arguments:

f u n c t o r ( arg1 , arg2 , . . . )

I However, there are situations where having a different positioncan make the programs easier to understand:

X i s f a t h e r o f Y

I In Prolog, one can define new operators by specifying:

I the position: whether the operator is prefix (default), infix orpostfix,

I the precedence: to decide which operator applies first (e.g. is2+3*4 (2+3)*4 or 2+(3*4)?), lower precedence binds thestrongest, precedences are between 1 and 1200,

I the associativity: e.g. is 8/2/2 (8/2)/2 or is it 8/(2/2)?I Note that logic predicates (i.e. those expressions that evaluate

to “true” or “false” are not associative in general). Consider:3 = 4 = 3, and suppose it were left associative, then (3 = 4)= 3 evaluates to “false” = 3, which changes the type of thearguments.

Operators in PrologI The usual way to write a Prolog predicate is to put it in front

of its arguments:

f u n c t o r ( arg1 , arg2 , . . . )

I However, there are situations where having a different positioncan make the programs easier to understand:

X i s f a t h e r o f Y

I In Prolog, one can define new operators by specifying:I the position: whether the operator is prefix (default), infix or

postfix,

I the precedence: to decide which operator applies first (e.g. is2+3*4 (2+3)*4 or 2+(3*4)?), lower precedence binds thestrongest, precedences are between 1 and 1200,

I the associativity: e.g. is 8/2/2 (8/2)/2 or is it 8/(2/2)?I Note that logic predicates (i.e. those expressions that evaluate

to “true” or “false” are not associative in general). Consider:3 = 4 = 3, and suppose it were left associative, then (3 = 4)= 3 evaluates to “false” = 3, which changes the type of thearguments.

Operators in PrologI The usual way to write a Prolog predicate is to put it in front

of its arguments:

f u n c t o r ( arg1 , arg2 , . . . )

I However, there are situations where having a different positioncan make the programs easier to understand:

X i s f a t h e r o f Y

I In Prolog, one can define new operators by specifying:I the position: whether the operator is prefix (default), infix or

postfix,I the precedence: to decide which operator applies first (e.g. is

2+3*4 (2+3)*4 or 2+(3*4)?), lower precedence binds thestrongest, precedences are between 1 and 1200,

I the associativity: e.g. is 8/2/2 (8/2)/2 or is it 8/(2/2)?I Note that logic predicates (i.e. those expressions that evaluate

to “true” or “false” are not associative in general). Consider:3 = 4 = 3, and suppose it were left associative, then (3 = 4)= 3 evaluates to “false” = 3, which changes the type of thearguments.

Operators in PrologI The usual way to write a Prolog predicate is to put it in front

of its arguments:

f u n c t o r ( arg1 , arg2 , . . . )

I However, there are situations where having a different positioncan make the programs easier to understand:

X i s f a t h e r o f Y

I In Prolog, one can define new operators by specifying:I the position: whether the operator is prefix (default), infix or

postfix,I the precedence: to decide which operator applies first (e.g. is

2+3*4 (2+3)*4 or 2+(3*4)?), lower precedence binds thestrongest, precedences are between 1 and 1200,

I the associativity: e.g. is 8/2/2 (8/2)/2 or is it 8/(2/2)?

I Note that logic predicates (i.e. those expressions that evaluateto “true” or “false” are not associative in general). Consider:3 = 4 = 3, and suppose it were left associative, then (3 = 4)= 3 evaluates to “false” = 3, which changes the type of thearguments.

Operators in PrologI The usual way to write a Prolog predicate is to put it in front

of its arguments:

f u n c t o r ( arg1 , arg2 , . . . )

I However, there are situations where having a different positioncan make the programs easier to understand:

X i s f a t h e r o f Y

I In Prolog, one can define new operators by specifying:I the position: whether the operator is prefix (default), infix or

postfix,I the precedence: to decide which operator applies first (e.g. is

2+3*4 (2+3)*4 or 2+(3*4)?), lower precedence binds thestrongest, precedences are between 1 and 1200,

I the associativity: e.g. is 8/2/2 (8/2)/2 or is it 8/(2/2)?I Note that logic predicates (i.e. those expressions that evaluate

to “true” or “false” are not associative in general). Consider:3 = 4 = 3, and suppose it were left associative, then (3 = 4)= 3 evaluates to “false” = 3, which changes the type of thearguments.

Operator syntax specifiers

Specifier Meaningfx Prefix, not associative.fy Prefix, right-associative.xf Postfix, not associative.yf Postfix, left-associative.xfx Infix, not associative (like =).xfy Infix, right associative (like comma in compound goals).yfx Infix, left associative (like +).

Commonly predefined Prolog operators

Priority Specifier Operators1200 xfx :−1200 fx :− ?−1100 xfx ;1050 xfy −>1000 xfy ,900 fy not700 xfx = \= == \== @< is = =<500 yfx + −400 yfx * / // mod200 xfy ˆ200 fy −

Example

%note th e s y n t a x o f d e c l a r i n g th e new o p e r a t o r :

:− op (100 , x fx , i s f a t h e r o f ) .

m i c h a e l i s f a t h e r o f kathy .X i s f a t h e r o f Y :− male (X) , p a r e n t (X, Y ) .

?− X i s f a t h e r o f kathy .

X = m i c h a e l .

I Read: the paper [Covington, 1989, Covington et al., 1997].

I Read: Section 6.6, of [Covington et al., 1997].

I Read: Sections 2.2, 2.3, 2.6, 2.10, 2.12, A.7of [Covington et al., 1997].

I Try out the examples in Prolog.

Covington, M. (1989).Efficient Prolog: A Practical Guide.Technical Report Research Report AI-1989-08, University ofGeorgia, Athens, Georgia.

Covington, M., Nute, D., and Vellino, A. (1997).Prolog Programming in Depth.Prentice Hall, New Jersey.

Wielemaker, J. (1990–2008).SWI-Prolog 5.6.60 Reference Manual.University of Amsterdam.

top related