Part IA Michaelmas Term
Procedural Programming Overview
Functional vs procedural
| Functional programming | Procedural programming |
|---|---|
| Expressions compute values | Commands transform state |
| No side effects | State mutation is the norm |
| Recursion for repetition | Loops (while, for) for repetition |
| Immutable data | Mutable variables, arrays, references |
What procedural programs do
Procedural programs repeatedly transform a program state by executing commands or statements. A state change might be:
- Updating a variable or array (local to the machine)
- Sending data to the outside world (output)
- Reading data from the environment (input, which also changes state by consuming data)
Building blocks
| Construct | Purpose |
|---|---|
| Assignment | Update variables: x := E |
| Input/Output | Communicate with environment |
if / match | Conditional execution |
while | Repetition |
| Procedures (functions) | Package commands as reusable abstractions |
The need for subroutines (procedures) was evident from the earliest days of programming. They represent one of the first examples of abstraction in programming languages.
OCaml’s blend
OCaml makes no distinction between commands and expressions. Everything is an expression that returns a value. However:
- Commands typically return
()of typeunit- the trivial value carrying no information. - The semicolon
;sequences expressions, discarding intermediate results. - OCaml programmers often use a functional style for internal computation and imperative features for I/O.
This dual nature means OCaml can teach procedural concepts while keeping the safety guarantees of a strongly typed functional language.