Declarative Programming (Cambridge (CIE) A Level Computer Science): Revision Note
Exam code: 9618
Declarative programming
How do I write declarative code?
Declarative programming is a paradigm where you describe what you want the program to accomplish, not how to do it
SQL is a common example of declarative programming
It allows you to extract and manipulate data using queries, without needing to specify the control flow
SQL was covered in more detail in Section 8 – SQL
Declarative code is made up of:
Facts – things that are known or assumed to be true
Rules – logical relationships between facts
Unlike imperative programming, where order and control flow are essential, declarative code allows you to define facts and rules in any order, and then write a query that uses them
In the following examples, a logic-based declarative language (like Prolog) is used
Example: Facts about dog breeds
type(beagle, hound).
type(labrador, retriever).
type(poodle, companion).
type(golden_retriever, retriever).
type(bulldog, companion).
size(beagle, medium).
size(labrador, large).
size(poodle, medium).
size(golden_retriever, large).
size(bulldog, medium).
shedding(beagle, moderate).
shedding(labrador, heavy).
shedding(poodle, low).
shedding(golden_retriever, heavy).
shedding(bulldog, low).
Interpreting clauses
Each fact uses the format:
predicate(object, property).
Clause | Meaning |
---|---|
| A poodle is a companion dog |
| A Labrador is a large-sized dog |
| A bulldog has low shedding |
Sample queries
Use queries to retrieve information from the facts
?- size(poodle, medium).
true.
?- type(X, retriever).
X = labrador ;
X = golden_retriever.
?- shedding(X, low), size(X, medium).
X = poodle ;
X = bulldog.
Key points
Concept | Description |
---|---|
Fact | A statement like |
Rule | A logical relationship built from facts (not shown here) |
Query | A question to the knowledge base, e.g. |
Any order | Facts and rules can appear in any order |
Result | The interpreter matches patterns in queries against known facts |
You've read 0 of your 5 free revision notes this week
Unlock more, it's free!
Did this page help you?