An Introduction To Declarative Programming in CLIPS and PROLOG
An Introduction To Declarative Programming in CLIPS and PROLOG
eCommons
Computer Science Faculty Publications Department of Computer Science
7-2019
Adam C. Volk
University of Nebraska - Lincoln
Saverio Perugini
University of Dayton, [email protected]
eCommons Citation
Watkin, Jack L.; Volk, Adam C.; and Perugini, Saverio, "An Introduction to Declarative Programming in CLIPS and PROLOG"
(2019). Computer Science Faculty Publications. 179.
https://ecommons.udayton.edu/cps_fac_pub/179
This Conference Paper is brought to you for free and open access by the Department of Computer Science at eCommons. It has been accepted for
inclusion in Computer Science Faculty Publications by an authorized administrator of eCommons. For more information, please contact
[email protected], [email protected].
Int’l Conf. Scientific Computing | CSC’19 | 105
An Introduction to
Declarative Programming in CLIPS and PROLOG
Jack L. Watkin, Adam C. Volk1 , and Saverio Perugini2
1 Department of Mathematics, University of Nebraska Lincoln, Lincoln, Nebraska, USA
2 Department of Computer Science, University of Dayton, Dayton, Ohio, USA
Programming Languages
Abstract— We provide a brief introduction to CLIPS—a
declarative/logic programming language for implementing
expert systems—and PROLOG—a declarative/logic program-
ming language based on first-order, predicate calculus. Un- Procedural Non-procedural
like imperative languages in which the programmer specifies
how to compute a solution to a problem, in a declarative Imperative Functional
Non-declarative Declarative
language, the programmer specifies what they what to find, C LISP
and the system uses a search strategy built into the language. Artificial Rule Based Logic
We also briefly discuss applications of CLIPS and PROLOG. Neural
Systems CLIPS PROLOG
1. Introduction
C LIPS1 is a declarative/logic programming language for both declarative programming language and, thus, involve
implementing expert systems. Originally called NASA’s the declaration of facts and rules, they each use fundamen-
A rtificial I ntelligence L anguage ( NAIL), CLIPS started as a tally different search strategies.
tool for creating expert systems at NASA in the 1980s. An
expert system is a computer program capable of model-
ing the knowledge of a human expert [1]. CLIPS stands 2.1 Horn Clauses
for C Language Integrated Production System. In artificial
intelligence, a production system is a computer system Logic programming in PROLOG is based on first-order,
which relies on facts and rules to guide its decision mak- predicate calculus—a formal system of logic which uses
ing. Programming in a declarative, rule-based language variables, predicates, quantifiers, and logical connectives
like CLIPS is fundamentally different than programming to produce propositions involving clauses. Clausal form is
in more traditional programming languages like C or Java a standard (and simplified) form for propositions: B1 ∨
and more resembles programming in PROLOG [2], [3], [4], B2 ∨ · · · ∨ Bn ⊂ A1 ∧ A2 ∧ · · · ∧ Am . The As and Bs
[5]—a declarative/logic language to which we compare are terms. The left hand side is called the consequent,
CLIPS throughout this paper.2 Fig. 1 situates CLIPS (and while the right hand side is called the antecedent. The
PROLOG ) in relation to other programming paradigms and interpretation is: if all of the As are true, then at least
languages [6]. one of the Bs must be true. Advantages of representing
propositions in clausal form are (i) existential quantifiers are
2. Declarative/Logic Programming unnecessary; (ii) universal quantifiers are implicit in the use
In the declarative paradigm of programming, rather than of variables in the atomic propositions; (iii) no operators
describing how to compute a solution as done when pro- other than conjunction and disjunction are required; and
gramming in, e.g., Java, the programmer describes what a (iv) all predicate calculus propositions can be converted to
solution to a problem looks like through the declaration of clausal form. “When propositions are used for resolution,[—
facts and rules describing it. While CLIPS and PROLOG are a rule of inference discussed below—]only a restricted kind
of clausal form called a Horn clause can be used, which
1 http://www.clipsrules.net/
further simplifies the resolution process” [7]. Horn clauses
2 P ROLOG , which stands for PROgramming in LOGic, is a declarative/- conform to one of the three forms detailed in Table 1 [8].
logic programming language developed in the early 1970s for artificial
intelligence applications. The PROLOG interpreter assumed in this paper All expressions in PROLOG match one of these three forms
is SWI - PROLOG—http://www.swi-prolog.org/. for Horn clauses.
Cite as: Watkin, J.L., Volk, A.C., & Perugini, S. (2019). An introduction to declarative programming in CLIPS and PROLOG . In Arabnia,
H.R., Deligiannidis, L., Grimaila, M.R., Hodson, D.D., & Tinetti, F.G. (Eds.), Proceedings of the International Conference on Scientific
Computing (CSC), 105–111. USA: CSREA Press. (Publication of the World Congress in Computer Science, Computer Engineering, and
Applied Computing (CSCE). Available at https://csce.ucmss.com/cr/books/2019/LFS/CSREA2019/CSC2488.pdf.)
106 Int’l Conf. Scientific Computing | CSC’19 |
Fig. 2: Architectural design of CLIPS (adapted from [6]). Similarly, we can declare the rule ‘If it is raining, then I
carry an umbrella’ in PROLOG with the rule.
carry(umbrella) :− weather(raining).
2.2 Asserting Facts and Rules
Additionally, consider the following set of facts and rule in
Like PROLOG, in CLIPS expert systems, knowledge is
PROLOG :
represented as facts and rules and, thus, a CLIPS or PROLOG
color(red).
program consists of facts and rules. A fact is an axiom that color(yellow).
is asserted as true. A rule is a declaration expressed in the color(blue).
form of an IF THEN statement. For example, a fact may lightcolor(X) :− color(yellow).
be ‘It is raining.’ In CLIPS this fact is written as:
(assert (weather raining))
These facts assert that red, yellow, and blue are colors. The
rule declares that yellow is a light color.
The assert keyword defines facts, which are inserted in
FIFO order into the fact-list. Facts can also be added 2.3 Resolution and Unification
to the fact-list with the deffacts command. An The Match-Resolve-Act cycle is the foundation of the
example rule is ‘If it is raining, then I carry an umbrella’: CLIPS inference engine which performs pattern matching be-
(defrule ourrule tween rules and facts through the use of the Rete Algorithm.
(weather raining)
=>
Once the CLIPS inference engine has matched all applicable
(assert (carry umbrella))) rules, conflict resolution occurs. Conflict resolution is the
process of scheduling rules that were matched at the same
The following is the general syntax of a rule [1]3 :
time. Once the actions have been performed, the inference
(defrule rule_name
(pattern_1) ; IF Condition 1 engine returns to the pattern matching stage to search for
(pattern_2) ; And Condition 2 new rules that may be matched as a result of the previous
.
. actions. This process continues until a fixed point is reached.
(pattern_N) ; And Condition N In PROLOG, however, the user gives the inference engine
=> ; THEN
(action_1) ; Perform Action 1 a goal that it then sets out to satisfy (i.e., prove) based on
(action_2) ; And Action 2 the knowledge base of facts and rules. To run a program,
.
. the user supplies one or more goals, each in the form of a
(action_N)) ; And Action N headless Horn clause (see Table 1). The activity of supplying
The CLIPS shell can be invoked in UNIX-based systems a goal can be viewed as asking questions of the program
with the clips command. From within the CLIPS shell, or querying the system as one does with a database system.
the user can assert facts, defrules, and (run) the When a goal is given, the inference engine attempts to match
inference engine. When the user issues the (run) com- the goal with the head of a headed Horn clause, which can
mand, the inference engine pattern matches facts with rules. be either a fact or a rule. P ROLOG works backward from
If all patterns are matched within the rule, then the actions the goal using a rule of inference called resolution to find
associated with that rule are fired. To load facts and rules a series of facts and rules which can be used to prove the
from an external file, use the -f option (e.g., clips -f goal. This approach is called backward chaining because
database.clp). Table 2 is a summary of commands the system works backward from a goal to find a path to
prove that the goal is true. C LIPS, on the other hand, works
3 Note that ; begins a comment. in the opposite direction. C LIPS takes asserted facts and
Int’l Conf. Scientific Computing | CSC’19 | 107
above. Specifically, since PROLOG clauses are evaluated (test (> ?x 0))
=>
from left to right, Z will never be bound to a value. (assert (fact (− ?x 1) (* ?x ?y))))
?− path(X,Y).
X = a, When the facts for the rule facthelper are pattern
Y=b;
X = a, matched, ?x and ?y are each bound to a value. Next, the
Y=c; bound value for ?x is used to evaluate the validity of the fact
X = b,
Y=d; (test (> ?x 0)). When variables are bound within a
X = c, rule, that binding exists only within that rule. For persistent
Y=e;
X = a, global data, defglobal should be used as follows:
Y=d; (defglobal ?*var* = "" )
X = a,
Y=e;
ERROR: Stack limit (1.0Gb) exceeded Assignment to global variables is done with the bind
ERROR: Stack sizes: local: 1.0Gb, global: 17Kb, trail: 2Kb operator.
ERROR: Stack depth: 12,200,621, last−call: 0%, Choice points: 5
ERROR: Probable infinite recursion (cycle):
ERROR: [12,200,620] user:path(_4520, d) 3.2 Templates
ERROR: [12,200,619] user:path(_4540, d)
Templates are used to associate related data (e.g., facts)
The resolution tree in Fig. 3 illustrates this idea. The left- in a single package—similar to structs in C. Templates
to-right evaluation strategy of clauses causes this tree to be are containers for multiple facts, where each fact is a
searched in a depth-first fashion, which leads to an infinite slot in the template. Rules can be pattern matched to
expansion of the rule. Rules are also pursued in a top- templates based on a subset of a template’s slots. Below
down fashion. Thus, if we reverse the two rules defining is a demonstration of the use of pattern matching to select
the path predicate given above, the stack overflow occurs specific data from a database of facts.
immediately without any output:
(deftemplate car
path(X,Y) :− path(Z,Y),edge(X,Z). (slot make
path(X,Y) :− edge(X,Y). (type SYMBOL)
(allowed−symbols
truck compact)
?− path(X,Y). (default compact))
ERROR: Stack limit (1.0Gb) exceeded (multislot name
ERROR: Stack sizes: local: 1.0Gb, global: 16Kb, trail: 2Kb (type SYMBOL)
ERROR: Stack depth: 6,710,347, last−call: 0%, (default ?DERIVE)))
Choice points: 6,710,342 (deffacts cars
ERROR: In: (car (make truck)
ERROR: [6,710,347] user:path(_4384, _4386) (name Tundra))
ERROR: [6,710,346] user:path(_4404, _4406) (car (make compact)
ERROR: [6,710,345] user:path(_4424, _4426) (name Accord))
ERROR: [6,710,344] user:path(_4444, _4446) (car (make compact)
ERROR: [6,710,343] user:path(_4464, _4466) (name Passat)))
ERROR:
ERROR: Use the −−stack_limit=size[KMG] (defrule compactcar
command line option or (car (make compact)
ERROR: ?− set_prolog_flag(stack_limit, 2_147_483_648). (name ?name))
to double the limit. =>
(printout t ?name crlf))
Thus, it is important to ensure that variables can be bound
to values during resolution before they are used recursively.
3.3 Conditional Facts in Rules
3. Going Further in CLIPS Pattern matching need not match an exact pattern. Logical
We briefly discuss three programming language concepts operators—or (|), and (&), and not (~)—can be applied
that are helpful in CLIPS programming. to pattern operands to support conditional matches. The
following rule demonstrates the use of these operators:
3.1 Variables (defrule walk
Variables in CLIPS are prefixed with a ? (e.g., ?x). (light ~red&~yellow) ; if the light
; is not yellow and
Variables need not be declared explicitly. However, variables ; is not red
must be bound to a value before they are used. Consider the (cars none|stopped) ; no cars or stopped
=>
following program that computes a factorial: (printout t "Walk" crlf))
(defrule factorial
(factrun ?x)
=>
(assert (fact ?x 1)))
4. Applications of CLIPS and PROLOG
(defrule facthelper
We briefly introduce some applications of CLIPS and
(fact ?x ?y) PROLOG .
Int’l Conf. Scientific Computing | CSC’19 | 109
4.1 Decision Trees the next vertex in the list. A cycle is a chain in which the
An application of CLIPS is decision trees. More generally, final vertex is adjacent to the first.) Consider the following
CLIPS can be applied to graphs that represent a human PROLOG predicates:
decision-making process. Facts can be thought of as the subgraph([Vset1,Eset1], [Vset2,Eset2]) :−
graph([Vset1,Eset1]), graph([Vset2,Eset2]),
edges of these graphs, while rules can be thought of as the subset(Vset1,Vset2), subset(Eset1,Eset2).
actions or states associated with each vertex of the graph. An
has_cycle(Graph, Vertex) :− chain(Graph, Vertex, Vertex, _).
example of this decision-making process is an expert system
that emulates a physician in treating, diagnosing, and ex- cycle_vertices(G, [V1|Vset]) :−
has_cycle(G, V1); cycle_vertices(G, Vset).
plaining diabetes [9]. The patient asserts facts about herself
including eating habits, blood-sugar levels, and symptoms. has_cycle([[V1|Vset], Eset]) :−
cycle_vertices([[V1|Vset],Eset], [V1|Vset]).
The rules within this expert system match these facts and
provide recommendations about managing diabetes in the Note that the above predicates make use of the chain
same way a physician may interact with a patient. predicate which checks if there is a path from a start vertex
to an end vertex in a graph. As stated above, a cycle is a path
4.2 Graphs where the start vertex and end vertex are the same vertex.
We can model graphs in PROLOG using a list whose Note that here we model edges of the graph as a list of lists.
first element is a list of vertices and whose second element If edges are modeled as facts, a different cycle predicate
is a list of directed edges, where each edge is a list of must be defined:
two elements—the source and target of the edge. Using edge(a,b).
this list representation of a graph, a sample graph is: edge(b,a).
edge(a,c).
[[a,b,c,d],[[a,b],[b,c],[c,d],[d,b]]]. edge(c,d).
Consider the following definitions of the primitive edge(d,a).
append and member predicates, which we use in subse- cycle(Start, Visited) :−
quent examples, with sample queries and outputs: cycle(Start, Start, [Start], Visited).
?− member(4, [2,4,6,8]).
As final examples, we illustrate predicates for identifying
true . a graph with no edges (or an independent set) and a complete
graph. (An independent set is a graph with no edges, or a set
Using the append and member predicates (and others not
of vertices with no edges between them. A complete graph
defined here, e.g., flatten and makeset), we define a
is a graph in which each vertex is adjacent to every other
graph predicate:
vertex.) These two classes of graphs are complements of
graph([Vertices,Edges]) :− checkDuplicateEdge(Edges),
flatten(Edges, X), makeset(X, Y), subset(Vertices, Y).
each other. To identify an independent set, we must check if
the edge set is empty. On the other hand, a complete directed
edge([Vset,Eset], Edge1) :−
graph([Vset,Eset]), member(Edge1, Eset).
graph has no loops, but all other possible edges. A complete
directed graph with n vertices has exactly n × (n − 1) edges.
vertex([Vset,Eset], Vertex1) :−
graph([Vset,Eset]), member(Vertex1, Vset).
Thus, we can check if a graph is complete by verifying that a
valid graph has no self-edges and that the number of edges
The graph predicate tests whether a given input represents satisfies this condition. The following are independent
a valid graph by checking if there are no duplicate edges and complete predicates, and helper count and proper
and that the defined edges do not use vertices which are predicates, for implementing these tests:
not included in the vertex set. The edge predicate takes a /* count number of elements in a list */
graph and an edge and returns true if the graph is valid and count([],0).
count([_|X], Y) :− count(X, Z), Y is Z+1.
the edge is a member of that graph’s edge set, and false
otherwise. The vertex predicate serves the same purpose /* for graph with X vertices , checks if X(X−1) edges */
proper(Y, X) :− Z is Y − X*(X−1), Z == 0.
for vertices. These predicates serve as building blocks from
which we can construct more interesting predicates. For /* checks if graph is an independent set */
independent([Vset, []]) :− graph([[Vset], []]).
example, we can check if one graph is a subgraph of another
one. We can also check whether or not a graph has a cycle /* checks if graph is complete ( infinite recursion problem) */
complete([Vset,Eset]) :−
in general or a cycle containing a given vertex. (A chain graph([Vset,Eset]), not(member([X,X], Eset)),
is a list of vertices such that each vertex is adjacent to count(Vset, X), count(Eset, Y), proper(Y, X).
110 Int’l Conf. Scientific Computing | CSC’19 |
noun_phrase(NP) :−
append(ART, NP2, NP), det(ART), noun_phrase_adj(NP2).
CLIPS>
One drawback of using PROLOG to implement a parser
is that left-recursive grammars cannot be implemented for 2) Rewrite the factorial program in § 3.1 so that only the
the same reasons discussed in § 2.3. Other applications of fact with the final result of the factorial rule is stored
PROLOG include Petri nets, recommender systems, and deep in the fact list. Note that retract can be used to
learning [10]. remove facts from the fact list.
Int’l Conf. Scientific Computing | CSC’19 | 111
?− mux("1", "2", "3", "4", 0, 1, Output). [1] J. C. Giarratano, CLIPS User’s Guide. Cambridge, MA: The MIT
Output = "2".
Press, 2008.
2) Define a PROLOG predicate that takes two cities [2] P. Brna, “Prolog programming: A first course,” 2001, available from
https://courses.cs.washington.edu/courses/cse341/03sp/brna.pdf [Last
and a route and determines if that route is a valid. accessed: 22 May 2019].
Excluding fact declarations, this program should be [3] W. Clocksin and C. Mellish, Programming in Prolog, 5th ed. Berlin,
approximately 15 lines of code. The roads need not Germany: Springer-Verlag, 2003.
[4] M. Kifer and Y. Liu, Eds., Declarative Logic Programming: Theory,
be implicitly bi-directional. Systems, and Applications. New York, NY: ACM and Morgan &
Sample list of cities: Claypool, 2018.
road(paris, rouen). [5] F. Pereira, “A brief introduction to Prolog,” ACM SIGPLAN Notices,
road(paris, lyon). vol. 28, no. 3, pp. 365–366, 1993.
road(lyon, marseille). [6] J. Giarratano and G. Riley, Expert systems principles and program-
road(marseille, nice). ming. Boston, MA: PWS Publishing Company, 1998.
road(paris, bordeaux).
road(paris, caen).
[7] R. Sebesta, Concepts of Programming Languages, 9th ed. Boston,
road(bordeaux, madrid). MA: Addison-Wesley, 2010.
road(madrid, cuenca). [8] P. Lucas and L. van der Gaag, Principles of expert systems. Boston,
MA: Addison-Wesley, 1991.
Examples: [9] M. Garcia, T. Gandhi, J. Singh, L. Duarte, R. Shen, M. Dantu,
S. Ponder, and H. Ramirez, Esdiabetes (an Expert System in Diabetes).
?− route(paris, caen, [paris, caen]).
true . Consortium for Computing Sciences in Colleges, 2001.
[10] J. Eckroth, AI Blueprints: How to build and deploy AI business
?− route(paris, cuenca, Route). projects. Packt Publishing, 2018.
Route = [paris, bordeaux, madrid, cuenca]. [11] C. Matthews, An introduction to natural language processing through
Prolog. London, United Kingdom: Longman, 1998.
3) Define a PROLOG predicate which takes an infix [12] J. Eckroth, “AI education matters: Biductive computing with Prolog,”
arithmetic expression and an integer and determines AI Matters, vol. 5, no. 1, pp. 14–16, 2019.