a paradigm is a typical example or pattern of something; a pattern or model. the programming paradigms we are going to look at are:
languages usually support a mix and possibly all programming paradigms. some languages are designed to favor one paradigm. for example java with object-oriented programming. some ways in which languages make it more difficult to use alternative paradigms are:
for example requiring to create files with classes to be able to create functions
unsupported features, for example no support for first-class functions domain- and problem-specific built-ins
series of commands that modify a programs state
imperative commands structured into subroutines
structure a program into objects with behaviour and data. or: both subroutines and data stored in records
describe "what" and not exactly "how"
treat computation as the evaluation of mathematical functions
express facts and rules and ask the system
avoids having to deal with goto by using subroutines
avoids having to deal with subroutines that modify global state by encapsulating data via classes in objects. classes act as templates for new objects
the factorial function implemented in different styles. each example shows definition then application. the factorial function calculates the product of all positive integers less than or equal to n
factorial(5) = 5 * 4 * 3 * 2 = 120
factorial = (n) -> result = 1 while n >= 1 result = result * n n = n - 1 result
class Factorial result: null calculate: (n) -> @result = 1 while n >= 1 @result = @result * n n = n - 1
f = new Factorial f.calculate 5 f.result
factorial = (n) -> if n <= 1 then 1 else n * factorial(n - 1)
factorial = (n) -> [1..n].reduce (result, n) -> result * n
factorial(0,1). factorial(N,F) :- N > 0, N1 is N - 1, factorial(N1,F1), F is N * F1.
?- factorial(5, X).