Functional Programming: a programming paradigm based on functions
Programming Paradigm: classification of programming approach based behaviour of code
Programming Paradigm: classification of programming approach based behaviour of code
Features of functional languages
Program State: the state of the machine at any given time
Typically described as the contents of variables
# imperative.rb
x = x + 1
a[0] = 42
i++
Imperative: State is mutable, changing or destructive
Imperative: State is mutable, changing or destructive
Can cause side effects (which is bad)
# side_effects.rb
@count = 0
def f(node)
node.data = @count
@count+=1
@count
end
No Referential transparency: replace expression with value with no side effects
f(x) + f(x) + f(x) != 3 * f(x) != 1 + 2 + 3
Imperative: State is mutable, changing or destructive
Reality Check: No single state exists
# states.c
int x = 1;
if (fork() == 0)
x = x + 1;
else
x = x * 5;
wait(NULL)
printf("x: %d\n", x);
Functional Programming has immutable state
Functional Programming uses immutable state
Our First Ocaml Program
(* hello.ml *)
print_string "Hello World!\n"
OCaml is a compiled language
ocamlc hello.ml
Helpful Programs
Probably want to run dune utop src
Will need to use ;; to end epxressions in utop
Rememeber Syntax vs Semantics
Everything is an expression (e)
1 + 3
the expression 1+3 has type int
true
the value true has type bool
Expressions have types
Expressions have types
The if expression
(if e1:bool then e2:t else e3:t):t
Actual Syntax:
if e1 then e2 else e3
Static and Latent Typing
Expressions have types
functions are expressions
(* function.ml *)
let f x =
if x mod 2 = 0 then
1
else
0
;;
The expression f has type int->int
Type Inference: inferring a variable's type
(* function.ml *)
let f x =
if x mod 2 = 0 then
1
else
0
;;
Function Definition Syntax
let f x1 ... xn = e
Function Calling Syntax
f x1 ... xn
Function Calling Syntax
f x1 ... xn
Things that happen
(* factorial.ml *)
let rec f n =
if n = 0 then
1
else
n * fact (n-1)
;;
f 2;;
Type of f: int -> int
Type of f 2:int
Value of f 2: 2
More on Type Checking
Types are inferred by operations they use
(* types.ml *)
(* compare two same types *)
1 = 1
x = y
x > y
x < y
(* x and y must have the same type *)
(* int have operators *)
3 + 4
x - y
x * y
x / y
x mod y
(* floats have different ones *)
3.2 +. 4.
x -. y
x *. y
x /. y
(* Strings have some too*)
"hello" ^ " world"
(* latent typing means inference *)
let f x y = if x > y then x else y-4;;
(* int -> int -> int *)