9.1 Overview
This chapter gives a number of tips on how to organize your
programs for increased efficiency. A lot of clarity and
efficiency is gained by sticking to a few basic rules. This list is
necessarily very incomplete. The reader is referred to textbooks such
as [O’Keefe 90] for a thorough exposition of the elements of Prolog
programming style and techniques.
- Do Not write code in the first place if there is a library
predicate that will do the job.
- Write clauses representing base case before clauses
representing recursive cases.
- Input arguments before output arguments in clause
heads and goals.
- Use pure data structures instead of database changes.
- Use cuts sparingly, and only at proper places
(see ref-sem-ctr-cut). A cut should be placed at the exact point that it
is known that the current choice is the correct one: no sooner, no
later.
- Make cuts as local in their effect as possible. If a
predicate is intended to be determinate, then define it as
such; do not rely on its callers to prevent unintended
backtracking.
- Binding output arguments before a cut is a common
source of programming errors. If a predicate is not steadfast, then it is
usually for this reason.
- Replace cuts by if-then-else constructs if the test is simple
enough (see Conditionals and Disjunction).
- Use disjunctions sparingly, always put parentheses around
them, never put parentheses around the individual disjuncts,
never put the ‘;’ at the end of a line.
- Write the clauses of a predicate so that they discriminate
on the principal functor of the first argument (see below).
For maximum efficiency, avoid “defaulty” programming (“catch-all”
clauses).
- Do Not use lists (
[…]
), “round lists” ((…)
),
or braces ({…}
) to represent compound terms, or
“tuples”, of some fixed arity. The name of a compound
term comes for free.
- Before trying to optimize your program for speed, use execution
profiling to get an idea of where most of the time is being spent,
and, more importantly, why.
Send feedback on this subject.