Download Prolog Programming A First Course
Transcript
54 Programming Techniques and List Processing This is a very desirable property for programs. For example, if we could write a program to determine that a given string of words was a legitimate sentence then we could use the same program to generate arbitrary grammatical sentences. Unfortunately, it not always possible to give a declarative reading to a Prolog program. 6.1.1 Evaluation in Prolog Unlike many programming languages, Prolog does not automatically evaluate ‘expressions’. For example, in Pascal, Y := 2 + 1; the term 2 + 1 is automatically evaluated and Y is assigned the value 3. Here is an attempt to do ‘the same thing’ in Prolog using =/2: Y = 2 + 1. with the consequence that the term 2+1 is unevaluated and the term Y is unified with the term 2+1 with the result that Y is bound to 2+1. Similar problems arise in relation to LISP. LISP will generally seek to evaluate expressions. For example, in (foo (+ 1 2) 3) LISP evaluates the term (s-expression) (foo (+ 1 2) 3) by evaluating (+ 1 2) to 3 and then evaluating (foo 3 3). A naive attempt to construct a similar expression in Prolog might look like: foo(1+2,3) but Prolog does not try to evaluate the term 1+2. Of course, there are times when evaluation is exactly what is wanted. Sometimes, particularly with arithmetic expressions, we want to evaluate them. A special predicate is/2 is provided. This predicate can be used as in: Y is 2 + 1. In this case, the term 2+1 is evaluated to 3 and Y is unified with this term resulting in Y being bound to 3. We can use is/2 to implement a successor relation: successor(X,Y):Y is X + 1.