tailieunhanh - Lecture Programming languages (2/e): Chapter 15b - Tucker, Noonan

Logic (declarative) programming allows a program to model a problem by declaring what outcome the program should accomplish, rather than how it should be accomplished. Chapter 15 provides knowledge of logic programming. In this chapter presents the following content: Practical aspects of prolog, prolog examples, symbolic differentiation, solving word puzzles. | Programming Languages 2nd edition Tucker and Noonan Chapter 15 Logic Programming Q: How many legs does a dog have if you call its tail a leg? A: Four. Calling a tail a leg doesn’t make it one. Abraham Lincoln Contents Logic and Horn Clauses Logic Programming in Prolog Prolog Program Elements Practical Aspects of Prolog Prolog Examples Symbolic Differentiation Solving Word Puzzles Natural Language Processing Semantics of Clite 5 Eight Queens Problem Practical Aspects of Prolog Tracing The Cut Negation The is, not, and Other Operators The Assert Function Tracing To see the dynamics of a function call, the trace function can be used. ., if we want to trace a call to the following function: factorial(0, 1). factorial(N, Result) :- N > 0, M is N - 1, factorial(M, SubRes), Result is N * SubRes. we can activate trace and then call the function: ?- trace(factorial/2). ?- factorial(4, X). Note: the argument to trace must include the function’s arity. Tracing Output ?- factorial(4, X). Call: ( 7) factorial(4, _G173) Call: ( 8) factorial(3, _L131) Call: ( 9) factorial(2, _L144) Call: ( 10) factorial(1, _L157) Call: ( 11) factorial(0, _L170) Exit: ( 11) factorial(0, 1) Exit: ( 10) factorial(1, 1) Exit: ( 9) factorial(2, 2) Exit: ( 8) factorial(3, 6) Exit: ( 7) factorial(4, 24) X = 24 These are temporary variables These are levels in the search tree The Cut The cut is an operator (!) inserted on the right-hand side of a rule. semantics: the cut forces those subgoals not to be retried if the right-hand side succeeds once. (bubble sort): bsort(L, S) :- append(U, [A, B | V], L), B 0, M is N - 1, factorial(M, SubRes), Result is N * SubRes. we can activate trace and then call the function: ?- trace(factorial/2). ?- factorial(4, X). Note: the argument to trace must .