CIE AS & A Level Computer Science, section 20.1 (Programming paradigms)
What declarative programming is
In declarative programming you state what you want (the facts, rules and the result needed), and the system works out how. There is no sequence of steps written by the programmer.
SQL
SQL is declarative: you describe the data wanted, and the database decides how to find it.
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE Pupil (Name TEXT, Mark INTEGER)")
db.executemany("INSERT INTO Pupil VALUES (?, ?)",
[("Aisha", 72), ("Ben", 45), ("Cara", 88)])
query = "SELECT Name FROM Pupil WHERE Mark >= 50 ORDER BY Mark DESC"
print(db.execute(query).fetchall()) # [('Cara',), ('Aisha',)]
Prolog (logic programming)
A Prolog program is made of facts and rules. A query asks the system to find answers.
parent(tom, bob).
parent(bob, ann).
parent(bob, joe).
female(ann).
grandparent(X, Z) :- parent(X, Y), parent(Y, Z).
sister(X, Y) :- parent(P, X), parent(P, Y), female(X), X \= Y.
?- grandparent(tom, W).
W = ann ;
W = joe.
- Facts: things that are true.
- Rules:
Head :- Condition1, Condition2.The head is true if all the conditions are true. The comma means AND. - Variables begin with a capital letter; atoms begin with a lowercase letter.
- The system uses unification (matching) and backtracking (trying other facts when one fails) to find all answers.
The same idea in Python
parent = [("tom", "bob"), ("bob", "ann"), ("bob", "joe")]
def grandparent(x):
return [z for (a, y) in parent if a == x for (b, z) in parent if b == y]
print(grandparent("tom")) # ['ann', 'joe']
Imperative and declarative
| Imperative | Declarative | |
|---|---|---|
| Programmer states | how | what |
| Control flow | written by the programmer | worked out by the system |
| Examples | Python, Pascal | SQL, Prolog |
| Suits | general programs | databases, knowledge bases, expert systems |
Common mistake: writing Prolog rules as if they were sequences of steps. A rule is a statement of truth: the head is true if the conditions are. Also, a capital letter starts a variable, so tom is a fact and Tom would be a variable.
Exam tip: for a Prolog rule, write the head, :-, then the conditions separated by commas, ending with a full stop. For a query, say which values the variable takes.
Check yourself
What is the difference between a fact and a rule in Prolog?
A fact states something that is true, whereas a rule says something is true if its conditions are true.
Why is SQL called declarative?
The query states what data is wanted, and the database system decides how to find it.
What does the comma between conditions in a Prolog rule mean?
AND, so every condition must be true.