Functional Programming

Programming Language Paradigms

Functional Programming

State

Basic OCaml

Basic OCaml

The Tuple (or Pair)

List Syntax in OCaml

Functional Example

Imperative Code

Functional-Style Advantages

Functional-Style Disadvantages

ML Innovative Features

Type System

Pattern Matching

Pattern Matching Mistakes

Polymorphism

Higher-Order Functions

Fold

Fold

Fold Examples

More Fold Examples

Map From Fold

let map f lst = fold (fun acc -> elt -> (f elt) :: acc) [] lst

Partial Application and Currying

Referential Transparency

Insertion Sort in OCaml

let rec insert_sort cmp lst =
  match lst with
  | [] -> []
  | hd :: tl -> insert cmp hd (insert_sort cmp tl)
and insert cmp elt lst =
  match lst with
  | [] -> [elt]
  | hd :: tl when cmp hd elt -> hd :: (insert cmp elt tl)
  | _ -> elt :: lst

Sorting

Functional Programming Summary