CSCI 208 - Programming Language Design
Language Paradigms
Imperative
Basics: a list of operations to do in order to accomplish a task.
Languages: C, Pascal, Ada, Fortran, Modula-2, Basic, Java
Good for: Accessing hardware, Operating Systems, I/O
Example: C
// Take the average of a list of integers
int average(int[] list, int length) {
int answer = 0;
for (i=0; i < length; answer += list[i]);
answer \= length;
return answer;
}
Declarative
Basics: a definition of a task and the computer will figure out the operations.
Languages: Haskell, OCaml, Prolog
Divided into two sub-categories: Functional and Logical
Functional
Basics: based on a mathematical lambda calculus "language". Everything is
recursive if possible.
A function is base cases and general (recursive) cases
Languages: Lisp, Scheme, ML, Haskell, OCaml
Good for: Math formulas
Example: Haskell
Take the average of a list of integers
> average :: [Int] -> Int
> average list = (sum list) \ (length list) <-- General case only
> sum :: [Int] -> Int
> sum [] = 0 <-- Base case
> sum [h:t] = h + sum t <-- Recursive case
> length :: [Int] -> Int
> length [] = 0 <-- Base case
> length [h:t] = 1 + length t <-- Recursive case
Logical
Basics: based on symbolic logic.
A set of statements describing what's
true about the desired result. Also uses a lot of recursion.
Languages: Prolog
Good for: Finding relationships (databases)
Example: Prolog
// Take the average of a list of integers
average(List,A) :- sum(List,S),
length(List,L), A is S/L. <-- General case only
sum([],0). <-- Base case
sum([H|T],S) :- sum(T,T_sum), S = H + T_sum. <-- Recursive case
length([],0). <-- Base case
length([H|T],S) :- sum(T,T_sum), S = 1 + T_sum. <-- Recursive case
Object Oriented
Basics: groups of communicating bubbles full of data and methods on the data.
Languages: C++, Java, SmallTalk, Alice, Ocaml
Example: C++ (Imperative)
// Take the average of a list of integers
class IntList {
public:
IntList();
IntList(int[] list, int length);
int average();
int max();
int min();
int mode();
private:
int * list;
int length;
};
int IntList::average() {
int answer = 0;
for (i=0; i < length; answer += list[i]);
answer \= length;
return answer;
}
Example: Ocaml (Functional)
(* Take the average of a list of integers *)
class IntList (list_init : int list) = (* Constructor takes a list *)
object
val mutable list = list_init (* OCaml cheats and uses member data *)
method average = (sum list) / (length list)
method sum (list: int list) =
match list with
[] -> 0
head :: tail -> head + (sum tail)
method length (list: int list) =
match list with
[] -> 0
head :: tail -> 1 + (length tail)
end;;
(*
OCaml figures out the return types for you
method sum : int list -> int
*)