Você está na página 1de 5

IEEE TENCON '93 / Beiinx

INTELLIGENT CONTROL FOR PROLOG


Young K. N a m and Kyusang Shin Software Development Automation Lab. Systems Engineering Research Institute/KIST Taejon, Korea

Abstract
We propose an extension to Prolog called the count term for controlling Prolog execution. The purpose is to allow the programmers as well M the users to have greater flexibility in controllin the execution behavior of Prolog programs and for limiting the number of answers a database query lanretrieved when Prolog is used guage. Both syntax and operational semantlcs of the count term are defined. We analyse the possible meanings one might associate with the count term. The poasible replacement of cut and jail by the count term is presented. The CMC of analysis of programs with count terms is discussed.

Prolog, (fenerally, transfers control to u in two " ways - u p icitly and implicitly. When an interpreter asks about getting another anewer, the progunmcr/a#r explicitly controls the backtracking behavior via the w e o the semicolon thst prompts the pr ram f r additional f o answera. If cut# or jailr are insert3 in the bodia of clauses, then the program is controlled implicitly. We introduce an new term, called the count term, which can replace both the explicit and im licit control of a program more declaratively and clear& by allowing the uaer to specify a priori the number of answers required for the given query. The count terms slso increara the efficiency of programs in some CMW. We believe that, by representing the count term in the given program explicitly, most CMW o c r t and fail u ~ g a Prolog can f in e eliminated. The syntax and operational lemantiu o the count f term are presented in Sections 2. We consider the &ble replacements and extensions of cut by the count krm in Section 3. Other applications of the count term d l be considered in Section 4.

Introduction

For the last decade, Prolog, one of logic programming languages, hm been acclaimed by many researchers for a ita clear and declarative nature and separation of program logic from control. But some impure language conBtructs such M cut and jail, which have been introduced to alleviate various difficulties with Prolog, seriously undermine the declarative nature of Prolog. In addition to control constructs, the undecidable nature of logic programs makes it difficult to completely analyse a given progtam for such features as type, mode and sementics. A clear understanding and analysis of these features would provide a better programming environment for programmers and users.

Syntax and Semantics of T h e Count Term

On the other hand, in addition to being the most commonly used implementation of logic programming languages, Prolog has been advocated by man researchers as a suitable query language for deductive %tabases (31. As a query language, Prolog would return all answers to a given query by backtracking through all possible branches in the SLD search tree. It has been recognised s for some time that in many database applications it i not feasible or even desirable that every possible answer' for a given query be returned. There exiats currently, however, no elegant way for a user/programmer to restrict the number of answers returned by the system for a given query. In most cases one needs to resort to the ude of non-logical devices such as refojor bagojto retrieve all answers anyway and then filter out any unwanted anmers. Clearly, this is a rather indficient solution.

The syntax we UIK for logic programs augmented with the count term is introduced in t h i section. We have a language 2 consisting of finik rets of C O M h t symbols, function symboln (with associated arities), pndicate symbols (with aaoociated arities), and infinitely many variables V. A t o m are defined in the-usual way (cf. Chang and Let 141). In addition, the language contains the connectives c and &. We do not deal with f negation here. Hence we concentrate on the claw o pure logic pro rams. The langua e also contains the ret o inf tegers A " T, denoted by @ ' which U the ret o e o u t f terms.

JT,

then A :p Definition 2 1 If A is an atom, and E NT, . 0 is a count annotated atom, abbreviated matom. Definition 2.2 A ea-clawe is a formula of the form:

Lo t L , k . . . & L ,
where LO is an atom and each L1,. ..,& U either an atom or a ca.-atom.

- 369 -

For eaeh Li,l < i < n that b an atom, we assume that it h a rhort 'f;anhfor Lc : T. Hence we may view the body of each ca-clause M consisting of all ca-atoms.

A program b a finite set of ca-clausa.

Here FSubst- denotes the set of finite and infinite sequences of finite substitutions. The details of the interpreter are shown in Figure 1. Explanations for each item in Figure 1 refer to [l3]. Figure 1: The Interpreter for Search n Times

S i c s the motivatbn for introducing the count term

rt-theoretic semantics based on model theory of first aider logfc [ l l ] ir insufficient. Debray and Mishra [ I have studied the semantics of S Prolog baaed on denotational scmantics. Their semantics take into account the usual Prolog depth-first, leftb r i g h t evaluation strategy, and hence is suitable for our purpose. The semantics we present will be based on the interpreten defined in [6]. Intuitively, the semantics is defined in terms of mequences of finite aubstitutiom for the goal variables. To the users, this is the only observable behavior of Prolog programs. Hence ven a query Q = c A i & . .&A,, and a program P, bray and Mishra's semantics would decree the meanin of Q to be a (possibly infinite) sequence of finite mkditutions (el,02,. ..,) .for the variables occurring in Ai,. ..,A,, and where el is the "first" substitution resulting frbm Prolog'a evaluations strategy. We denote by seq(Alk.. .&A,,) the above sequence of aubstitutions for the goal Q.

1. interp(nil, P, q ) = intcrp(St,P, 0) = nil 2. interp((nil,d,C, 0) I: (((A, p) :: G , V P ) :: F,e, c, ::s t a ,P, v(#0)) = f) 4 :: interp((((A, ::G , VP)::F,O, C, ) ::Sta, P, q p) 1
1) 3. interp((((A,p) G,Vp) :: Fo,#,nil,O) : ( ( ( L , p ): :: : :

Gi,V;)::Fi,8,Ci,f')::Sto,P,q(# 0)) = interp((((L,P): G I V;) : 4 , B , Cl, f) ::Sto, P, q) : , : ' 4. interp((((A,p) G,Vp) : Fo,#,nil,l) :: ( ( ( L , p ):: :: :

G ~ , V ; ~ : : ~ ~ , ~ , C ~0)) ~ ~ ~ : : S ~ ~ , P , ~ ( ~ , =
5.

interp((((L,P.l) 01, V;) : Fi, 0, C , ::Sto, PIq) :: : i f') interp((((A,p)::G,Vp)::Fo,d,(Ho o ) : : C , f ) : : :- B sto, p , v(# 0)) = i n t e r p ( ( F ~ : : F i : : F o , B o d , P , O ) : : S t l , Pwhere ,q)
p#O; Hi: - I31 = rename((H0 : - Bo),dom(#)); 0 = unify(+(A), Hi)# fail;

The formal operational semantics of the count term can be apecified via a simple change to the cut-free interpreter defined in [ I We first recap aome definitions. S. The interpreter operates on a stack. The stack completely specifies the state of execution of the interpreter. Each element in the stack is called a record which consists of a h m e L i r t , a substitution, a list of clauses, a flag indicating whether one of its children has an answer or not. Every time a stack is created, the value of the tlag is set to rero. Its value is only set to one when an answer for the program is obtained. A FrameList is a nequence of h m e r and a Frame is a sequence of C-alomr as well as a met of variables denoting the bindings to be p~sed back to the calling goal. A C-atom consists of an Atom or Ca-atom and a count term. When the Catom is the Atom, the count term is set to T a t the time of paraing. In BNF notation, the state is defined as follows. where q E N T C-atomLMt ::= nil) a t o m :: C n t m L i s t Frame ::= (CatomList,V a r p ) FrameLid ::= nillFrame :: FrameList Stuch ::= nill(FrameLMt,Subst, Clause., flog) : : Stack State ::= Stack.
C d m ::= (Atom,

Vh = h ( 9 ) ; 4 = (Bi, Vh); 4 = (G,VP); Sti = ( ( ( A , p ): : G , V p ): : F o l d , C r f ) : : S t o . -B 8. interp((((A,p)::G,Vp)::Fo,#,(Ho: o ) : : C , f ):: sto, p , tl(# 0)) = interp((((A,p):: G,Vp) :: F o , d I C , f ):: Sto,P,q) where
P

H I : -B1 = rename((Ho : -Bo), dom(d)); B = unify(g(A),R I )= fail. 1. interp((((q0):: G,Vp) :: Fo,d,C,f) :: ( ( ( L , p ):: G I ,V;)::Fl,8, CI)::Sto, P,q(# 0 ) ) = interp((((L, i : : G ~ , ::4,e, C1, ::Sto, PIq ) p) v;) f') 8. interp(((niI,Vp):: Fo,d,C,f) :: St,P,q(# 0)) = interp((&,d 1v ~ , c , f ) : : s t , P , r l ) .

# 0;

3
3.1

Count Term vs. CUT


Count Term as an Alternative t o Cut

Some explanation of the notation is warranted. The denotes the usual kleene closure operator. P in the given Prolog program. A :: B denotes a list whose first element is A and with B the rest of the (possibly empty) list. The interpreter m a function i

interp :State x Clause' x NT + FSubsP.

In Prolob, execution backtracks to the most recent backtrack point when unification fails. One problem that can arise with this simple control strategy is that execution may backtrack exhaustively through clauMs that cannot

- 370 -

contribute to a solution (in extreme cases, this can lead to logically correct programs going into M infinite loop). The cut construct returns some control over this backtracking behavior to the user. Operationally, the effect of a cut is to diseard certain backtrack points, so that execution can never backtrack into them. In practice, cuts are moat frequently encountered in one o two static conf texts: as part of the top-level conjunction in a clause or within a disjunction in a clause, i.e., either in a context
p:-... p :- I,.

It is possible, in principle, for cuts to be used in a wide variety of contexts. Among those una UI, most uns of cut can be categorised as one of the fofiowing [E];
Cuts to commit to a clause: the cut tends to be towards the beginning of the clause, possibly after some tests.. Cuts to force computations to be functions: the cut tends to appear towards the end of clause. Cuts to break out of failure-driven loop: in implementations lacking garbage collectors, loops using repeat/ fail constructs are used to reclaim space on the heap. Cuts are then used to break out o these f loops. The count term exactly mimicscut for case 2. Suppose we have several clauses with the name head predicate and each clause is functional and mutually exclusive, i.e. there can be a t most one solution for m y 4 1 to clauses (for further details of the function clause and mutual exclusion for non-recursive c l a u ~ refer to E]). Sup ose s also that some of the clauses have cut at t i e end orthe clause. Those clauses may not be functional without the cut. We can infer that the purpose of this procedure is to get only one solution and prevent backtrack for further solutions. For this kind of procedure, if we put the count term :1 at the end of the parent predicate which calls that procedure, then the cut can be removed without changing the semantics. The reason is that, by limiting the number of answers for the procedure to one, once a solution has been found, control is returned to the literal preceded by the current literal. Then, on the backtrack, the count term :1 becomes :O. In item 7 of Figure 1, if the count term of the top frame in the top element of the state stack becomes zero, then it pops up the top element of the state stack which includes all backtracking points. Therefore, it works exactly as the hard cut. With count trriirs the procedure i clenr in its context and enny to s read. One of the most frequently used kinds of program for this case is the cut attached a t the end of base clauses in a recursive program which may have several BMWCIS. Example 3 1 Member function. . member(X,[XIL]). member(X,[YIL]) :- member(X,L). :- member(b,[a,b,c,b,e,a,~).
(1) (2)

..., .
..

p:-.

or in a context p:-. p :- ...,((..., I,.. .); p:-...

..

1,. ' .

(a..)

There are two kinds of cut: The first one is referred to as the hard cut, which discards all those backtrack points set up by literals to the left of the cut all the way to the beginning of the clause and the backtrack point for the parent predicate whose definition includes the clause containing the cut, i.e. all remaining alternative clauses for this predicate. The second one is referred to as the soft cut, which discards the backtrack points set up by literals to the left of the cut in the clause but not the alternative clauses for the predicate. We assume that cuts occur in the above contexts statically and are used as hard cuts.
'I'hc ciit (I) which in currrritl u n r d to roiitrol tlir cxecution has several drawbacks re]. The foremost is that cuts often make programs considerably harder to understand declaratively. Another problem with the use of cuts is that because of their nonlocality, they do not interact gracefully with program transformation systems. For example, unfolding a predicate without considering the cuts included in the clause can result in the loss of some solutions. A third problem is that it does not allow the parallel execution of programs because of its sequential property, even if the underlying implementation allows parallel evaluation. In order to overcome these cJrawbacks, Debray [e] tried a source to source translation by replacing the cut with statements discarding choice points.

(3)

For example, the member function shown in exam le


3.1 checks whether a list in the second argument of [3)

Recall that the primary purpose of the count term is to limit the number of answers to be retrieved for the given query in the context of compilation. But whrn the count term is properly used in the body of the clause, it can control the execution of a program more declaratively and clearly so that umrs can improve the readability of program and generate code of good quality, without having to rely on the impure features of the cut. In this section, we discuss the possibility of replacing some usages of cut by count terms.

haa the first argument as one of its elements. Since in query (3) the second argument contains the first argument many times, this program would give several pes answers. If a programmer r a n t s only to know the existence of the first argument in the second argument, not how many times it appears, then cut is used to a t the end of (l),an in (4). member(X,[XIL]) :-1.
(4)

-371

In this kind of program, the count term can be uaed very dfatively and declaratively without cut by attachin (5). ing the count term at the end of the query
:-member(b,[a,b,c,b,e,af):l.

Other Applications of Count term


Type Analysis

the

(5)

4.1

Furthermore, we can check how many times the fint elcment-is contained in the w o n 4 argument of (5) by using different values for the count term.

32 .

Count Term as an Extension to Cut

Now we consider how to une count terms to control iterations. Generally, two types of iterations 'are used in Prolog; do until and for [15]. When "do until" hi used, it has the following format;

i t e r a t e ( P r e d ) :- r e p e a t , iterateZ(Pred) ,done. iterateZ(Pred) :- call(Pred), I . repeat-. repeat :- r e p e a t . Theae statements repeatedly query some predicate exeasion Pred until some other predicate expression done Elds. Another kind of iteration increases a counter a t each iteration, like the "FOR" construct in Pascal and the "DO"construct i Fortran which iterate for K=l to N: n foriterate(Pred,ll) :- asserta(connter(O)), repeat. comter(K). KZ is Ktl, r e t r a c t (connter(K) 1, aasesta(connter(K2) 1, i t e r a t e 2 ( P r e d ) , K2>=1, retract(counter(KZ)), ! iterateZ(Pred) :- (call(Pred)). !),l=l. repeat. repeat : r e p e a t .

Prolog is known aa a typelesr langu e. But type information helps program debugging execution speed. A type system in logic programming c o n b t s of t h m aspects: type declaration, tyg' inference, type checkin [18]. In this paper, we cons1 er only type inference a n ! type checking. However, complete type inference and the question of whether a program is well typed U undccidable. To our beat knowledge, there are no complete type systems no far. Recent research [17, 181 about type syatems restricts sdmehow their domain or range. In (ltl], Yardeni presented a type system based on a sound mathematical background. Rut it has a rwtriction that types are inferred and checked only for so called regular unary logic programs, which is a nubclass of lo@ p r o g r m . Xu, in [17], implemented a feasible type inference s y , tem using depth abstraction and ty e definitions with a normal theorem prover. They used L p t h abstraction bea u s of the non-termination property of Prolog. Them ~ are two reasons that lead to non-termination. The first one is that mme of the predicatw have an infinite number of anawers. The mccond one occun when a given rogram has a left recursion. For tholle problems, Xu an extension table technique [e] based on the functions. This method limited the number of repetitions of function symbols. For irutance, in example 4.1, if the number of repetitions of function symbok 'a' is given by 1, then the ty e inference rocedure stop when it has tuples {(c,X,X{(s(c),X,s(Xfi} for the type of predicate d.

a8

Example 4.1 Add function.

add(O,X,X). add(I( X) ,Y,a(Z)) :-add( X,Y, ) Z. This method is complete and sound under the limitation of function symbols but expores an unpractical problem. In the normal programming environment, usen are not able to p r d c t the number of repetitions of function symbols in a predicate. Furthermore, users may need a different number of a p pearances depending on clsuser or queries. To limit the appearance of all function symbok by the same number in not realistic and practical. We suggwt a method of inferring types by using the count krm. The idea is that with coud f e w we limit the number of types which a predicate can have. For instancet if the query for the type inference in example 4.1 U gven aa

This program has many side effect predicates assert and retrod in the loop, which make it harder to understand. Normally, when users can not figure out how many timea the body of the loop is called, the do until type is used. In that case the use of cuts is inevitable. But if for type iteration is used, then the iteration can be implemented without depending on cuts by concatenating the number of times at the end of the calling literal. The following two statementn can replace all six statements of the foriterate program without aide effects and cuts. foriterate(Pred) :- call(Pred):l. :- f o r i t e r a t e ( P r e d ) : I .

types for every predicate in the p r o p " Moreover, by changin the count terms for the given program, uocn can easify test and debug Prolog pro rams since the uocr can tell what makes the difference %etmen t y p a with different count term.

- 372 -

4.2

Mode Inference

Mode information, which indicates the type (input or output) of arguments of a literal in a rule, can be used by a compiler to effect various optimirations: allocation of 4lobal variables to the local )tack, essy unification with mode information, analysis of functionality o predicates and clauses, and program transformation, f etc. Like type inference, the non-termination mechanism of Prolog makes it expensive for com lete mode inference. There have been many papers agout mode lnference 11, 2, 7. Amon them Debray, in [7], sug1 gested a nice al orithm for fandling aliwing effects with an extension t a b e method [O] for automatic mode inferwce. Thus, his method, a t first, decides whether calling

[3] S. Ceri, G. Gottlob, and L. Tanca, Logic Programming and Databwcs, Survey. in Computer Science, New York Springer-Verhg, 1990. [4] C. L. Chang and R.C.T. Lee, Symbolic Logic and Mechanical Theorem Proving, Orlando: Academic Press, 1973. 11 W. Clocksin and C. Melish, Programming in PRO5 LOG, New york: Springer-Verlag, 1981.
[6] S.K. Debray and P. Mishra, "Denotational and O p

erational Semantics for Prolog," J . Logic Programming, vol. 5, 1988,pp. 61-91.

[7] S. K. Debray and D. S. Warren, "Automatic Mode Inference for Logic Programs," J. Logic Programming, vol. 5, 1988, pp. 207-229.

[E] S. K. Debray and D. S.Warren, "Towards Banishing the Cut from Prolog," IEEE tram. Software Eng.,
problem, Rruynooghe et al. have proposed a strategy for handling return-aliasin by duplicating literals in the body of the clause [l]. j u t this requires a source to source translation and makes it hard for users to underhand the program with duplicated literals. The method we want to suggest is to use the count term with a normal Prolog interpreter with the limited domainf,c,f,d! o terms i predicates without ode checking an dupli f s a t e literal insertion. vol. 16, Mar. 1990, pp. 335-349.

[ I S. W. Dietrich, "Extensiy Tables : Memo Relsr S tions in Logic Programs, Proceedingo of Symposium o n Logic Programming, San Francioco, 1987, pp. 264272.

[lo] T. Kanamori and T. Kawamora, "Analysing Success Patterns ofbogic Pro r a m by Abstract Hybrid Interpretation," Technic3 Report TR-179, ICOT, Japan, 1987. (111 J.W. Lloyd, Foundalionr of Logic Programming, New York Springer-Verlag, 1988.
[12] P. Miahra, "Towards a Theory of Typca in Prolog," Proceedings of the IEEE Iniernational Symposium on Logic Programming, 1984,pp. 289-298. [13] Y. K. Nam, L. j. Hennchen "A Debugging Facility for Prolog", Proceedings of the First International Workshop o n Automated and Algorithmic Debugging, Linkoping, Sweden, May 1993. I4 11

Conclusions

We have introduced the count term and m g ested a u method for controlling the execution of Profog programs. Its syntax and operational aemantics are presented. Also the possible replacements and extension of cuts by the count term are discussed. We believe that this term is very useful in Prolog M well M in deductive databases. Further extensions of this count krm, like "find the best answer" or "find the first or laat answer", and allowing c ( A l k &A,) : p or t- B i C . . AI&. kA,) :PkBik.. .Bm, Would make it more powerful and remains M a further study.

..

...

R. A. O'Kcefe, "On the treatment of cuts in PIlog source-level tools," in Proc. 1885 Symp. Logic Programming, Boston, MA,July 1986,pp. 73-77.

[15] N. Rome, 'Artificial Intelligence through Prolog," .. Englewood Cliffs, N J : Prentict-Ed, 1988. [l6] M. A. Van Emden and R. A. Kowalski, "The IKmantics of Predicate Logic an a Programming Language," JACM, vol. 23,no. 4,1976,pp. 733-742. [17] J. Xu and D. S. Warren, "A Type Inference System for Prolog," in International conference and Symposium o n Logic Programming, Seattle, Weahington, Aug. 1988, pp. 604819.

References
[l] M. Bruynooghe, B. Demoen, A. Callebaut, and 0 .
Janssens, "Abstraction Interpretation: Towards the Global Optimization of Prolog Programs ," in Proc. of the 4th IEEE Symposium on Logic Programming, San F r a n c ~ o CA, See. 1987. ,

[la] E. Yardeni and E. Shapiro, "A Type System for Logic Programs," J. Logic Programming, vol. 10,
1991, pp. 125-153.

[2] M. Bruynooghe and G. Janssena, 'An Instance of Abstract Interpretation Integrating Type and Mode Inferencing," in Proceedings of the 5 h International t Conference and Symposium on Logic Programming, Seattle, Wsrhington, Aug. 1988,pp. 669-683.

- 373 -

Você também pode gostar