Programming Paradigms
1. The Big Shift: What vs. How
A Paradigm is a style or "way" of programming. Most students are used to the Imperative style, but the 9618 syllabus requires proficiency in the Declarative style (specifically Prolog).
Imperative (Procedural)
Focuses on HOW to achieve a goal. You provide a sequence of instructions that change the program's state.
Examples: Python, C, PHP, Java.
Declarative
Focuses on WHAT the goal is. You describe facts and rules, and the computer uses an "Inference Engine" to find the answer.
Examples: Prolog, SQL, HTML.
Imperative: "Go to the kitchen, get two slices of bread, apply butter to one side, place a slice of ham in between..."
Declarative: "I would like a ham sandwich, please." (The system already knows what a sandwich is and how to make it).
2. Declarative Concepts: Facts and Rules
In Prolog (Programming in Logic), everything is built from three things:
- Facts: Unconditional truths.
parent(john, mary).(John is the parent of Mary). - Rules: Conditional truths using "IF" (written as
:-). - Goals/Queries: Questions you ask the system.
?- parent(X, mary).
Prolog Example: Family Tree
parent(john, mary).
parent(mary, ann).
% Rule: X is a grandparent of Z IF X is parent of Y AND Y is parent of Z
grandparent(X, Z) :- parent(X, Y), parent(Y, Z).
% Query (Goal)
?- grandparent(john, ann).
YES
3. Real-Life Declarative Tech
Students use declarative programming every day without realizing it:
- SQL: When you write
SELECT name FROM students WHERE grade = 'A', you aren't telling the database how to search the disk; you are just declaring what data you want. - HTML/CSS: You declare
<h1>Hello</h1>. You don't tell the browser how to paint the pixels or calculate font-weight; the browser's engine handles the "how."
This is a favorite A2 question. Backtracking is the process where the Prolog engine tries one path to satisfy a goal, and if it fails, it "goes back" to the last successful point and tries a different path. It's like navigating a maze by trial and error.