Bratko, Chapter 8: Programming Style and Technique 8.1 General principles of good programming - correctness (1) - efficiency (3) - readability (2) - modifiability (4) - robustness (5) - documentation (6) 8.2 How to think about Prolog programs - recursion - generalization - pictures 8.3 Programming style - style - clauses about same procedure clustered together - each goal on a separate line - use cut sparingly - try using only green cuts, i.e., cuts that can be removed without altering the declarative meaning of the program - red cuts only when selecting among alternatives - not(P) :- P, !, fail ; true. - if Condition then Goal1 else Goal2 - ( Condition, !, Goal1 ; Goal2 ) - avoid program modification by assert and retract - prefer multiple clauses to semicolons - example - merge(L1,L2,L3) (p194) (HW2, Spr95) - commenting - /* */ or % 8.4 Debugging - Prolog is interpretive, so any procedure in a program can be called directly - debugging through tracing goals - outputs entry information - predicate name - values of arguments - outputs exit information - on success, values of arguments - on failure, Fail - 'trace' - turn on tracing - 'notrace' - turn off tracing - spy(P) - trace only after encountering predicate P - P is the predicate name; all such predicates spied - can be executed multiple times - can use arity representation: man/1 or man/2 - nospy(P) - turn off tracing for predicates named P 8.5 Efficiency - compile your program using 'qpc' - ignore error about 'qld' - avoid unnecessary backtracking - stop execution of useless alternatives as soon as possible - caching - examples - reordering queens [1,2,3,4,5,6,7,8] -> [1,5,2,6,3,7,4,8] (p198) - reordering countries for map colouring (p199) - start with country having most neighbours - representing lists as differences - prevents backtracking on first list to find tail - concat(A1-Z1, Z1-Z2, A1-Z2) - concat([a,b,c | T1] - T1, [d,e | T2] - T2, L). T1 = [d,e|T2], T2 = _8970, L = [a,b,c,d,e|T2]-T2 ; - caching Fibonacci numbers (p203) - computing Fibonacci numbers bottom up (p205)