Introduction to Functional Programming Using OCaml Romain Bardou - - PowerPoint PPT Presentation

introduction to functional programming using ocaml
SMART_READER_LITE
LIVE PREVIEW

Introduction to Functional Programming Using OCaml Romain Bardou - - PowerPoint PPT Presentation

Introduction to Functional Programming Using OCaml Romain Bardou July 6, 2011 Introduction to Functional Programming Using OCaml 1 / 50 Introduction There are two ways to write error-free programs; only the third one works. Alan J.


slide-1
SLIDE 1

Introduction to Functional Programming Using OCaml

Romain Bardou July 6, 2011

Introduction to Functional Programming Using OCaml 1 / 50

slide-2
SLIDE 2

Introduction

There are two ways to write error-free programs;

  • nly the third one works.

— Alan J. Perlis

Introduction to Functional Programming Using OCaml 2 / 50

slide-3
SLIDE 3

let’s talk about

typing

Introduction to Functional Programming Using OCaml 3 / 50

slide-4
SLIDE 4

Typing

types capture:

◮ invariants about variables ◮ design intents of the programmer

examples of such invariants:

◮ some variable x always contains an integer ◮ some variable l always contains a list ◮ some variable l′ always contains a list of integers

types prevent errors such as:

◮ inserting a value into an integer (instead of a list) ◮ adding two lists together

Introduction to Functional Programming Using OCaml 4 / 50

slide-5
SLIDE 5

Typing: Example

(all examples in this talk are written in OCaml) let x: int = 5 in let y: int = x + 10 in let z: int list = y :: [ 1; 2; 3 ] in ... (note: type annotations can be omitted thanks to type inference)

Introduction to Functional Programming Using OCaml 5 / 50

slide-6
SLIDE 6

Typing: Example of Errors

you cannot add an integer and a list 5 + [ 1; 2; 3 ] (* type error *) you cannot insert an integer into an integer 42 :: 69 (* type error *) you cannot insert an integer into a list of lists of integers let x: int list = [ 1; 2; 3 ] in let y: int list list = [ [ 42; 69 ]; [ 4 ] ] in let z: int list list = x :: y in 10 :: z (* type error *)

Introduction to Functional Programming Using OCaml 6 / 50

slide-7
SLIDE 7

Typing is Done During Compilation

typing is done before the program is executed errors are found before the program is executed program is well-typed = ⇒ whole category of errors prevented

Introduction to Functional Programming Using OCaml 7 / 50

slide-8
SLIDE 8

let’s talk about

algebraic types

Introduction to Functional Programming Using OCaml 8 / 50

slide-9
SLIDE 9

Richer Types

types encapsulate invariants and design intents the richer types are, the richer the invariants types help the programmer to structure his data = ⇒ need richer types for more complex structures

Introduction to Functional Programming Using OCaml 9 / 50

slide-10
SLIDE 10

Algebraic Types: Product Types (a.k.a. Records)

type complex = { re: float; (* real part *) im: float; (* imaginary part *) } let add_complex (x: complex) (y: complex) = { re = x.re +. y.re; im = x.im +. y.im; } let x: complex = { re = 0.; im = 10. } let y: float = x.re let z = add_complex x 2 (* type error *) let t = x.toto (* type error *)

Introduction to Functional Programming Using OCaml 10 / 50

slide-11
SLIDE 11

Algebraic Types: Product Types (a.k.a. Tuples)

instead of declaring a record type, you can use tuples let add_complex (re1, im1) (re2, im2) = (re1 +. re2, im1 +. im2) let x: (float * float) = (0., 10.) let y = add_complex x 2 (* type error *) use pattern-matching to read the components of the tuple let ((z: float), (t: float)) = x let (z, t) = x let (_, _, u) = x (* type error *)

Introduction to Functional Programming Using OCaml 11 / 50

slide-12
SLIDE 12

Algebraic Types: Sum Types (a.k.a. Variants)

type atom = H | He | Li | Be | B | C | N | O type orbital = S | P | D | F let orbital_of_atom (a: atom): (orbital * int) = match a with | H | Li → (S, 1) | He | Be → (S, 2) | B → (P, 1) | C → (G, 2) (* type error: G not an orbital *) | O → (P, 4) (* type error: we forgot atom N *)

Introduction to Functional Programming Using OCaml 12 / 50

slide-13
SLIDE 13

Example: The Researcher Data Structure

possible solution: using a product type type researcher = { student: bool; (* true iff the researcher is a student *) name: string; phd_students: string list; }

Introduction to Functional Programming Using OCaml 13 / 50

slide-14
SLIDE 14

Example: The Researcher Data Structure

problem: ensure that students have no PhD students solution: use a sum type type researcher = | Student of string | Professor of string * string list

Introduction to Functional Programming Using OCaml 14 / 50

slide-15
SLIDE 15

Example: The Researcher Data Structure

to read the list of PhD students, we need pattern-matching let phd_students_of_researcher x = match x with | Student _ → [] | Professor (_, l) → l ensures students always have no PhD students ensures the programmer considers all cases

Introduction to Functional Programming Using OCaml 15 / 50

slide-16
SLIDE 16

Example: Lists

let’s define our own list type! type ’a mylist = | Empty | Cons of ’a * ’a mylist let empty_list = Empty let list_singleton = Cons ("coucou", Empty) let list_1_2_3 = Cons (1, Cons (2, Cons (3, Empty)))

Introduction to Functional Programming Using OCaml 16 / 50

slide-17
SLIDE 17

Example: Lists

compute the length of a list using a recursive function let rec length x = match x with | Empty → 0 | Cons (_, rem) → 1 + length rem note: typing prevents me from forgetting the empty case (not the case in languages with the NULL pointer)

Introduction to Functional Programming Using OCaml 17 / 50

slide-18
SLIDE 18

Polymorphism

type of function length: ’a list → int ’a can be instanciated with any type let x = length (Cons (1, Empty)) let y = length (Cons ("salut", Cons ("toi", Empty))) avoid code duplication, avoid errors

Introduction to Functional Programming Using OCaml 18 / 50

slide-19
SLIDE 19

Types: Conclusion

encode properties of your data structure in its type the compiler ensures you preserve the properties you thus avoid many programming errors algebraic types are quite expressive can often replace the heavy object paradigm polymorphism avoids code duplication ... and, as a consequence, error duplication

Introduction to Functional Programming Using OCaml 19 / 50

slide-20
SLIDE 20

let’s talk about

side-effects

Introduction to Functional Programming Using OCaml 20 / 50

slide-21
SLIDE 21

Variables Are Immutable

in OCaml, variables are immutable let x = 1 the value of x is now 1 until the end of time

Introduction to Functional Programming Using OCaml 21 / 50

slide-22
SLIDE 22

Variables Are Immutable

let x = 1 let x = 2 the first x is hidden the second x is atually another variable the code is comparable to: let x_1 = 1 let x_2 = 2

Introduction to Functional Programming Using OCaml 22 / 50

slide-23
SLIDE 23

References

a reference is a mutable value let x = ref 0 in x := 1; x := !x + 3

Introduction to Functional Programming Using OCaml 23 / 50

slide-24
SLIDE 24

Parenthesis: Initialization

must give an initial value to all variables, all references avoids errors such as: let x: int in (* not proper OCaml! *) if x = 0 then (* probably an error: x is not initialized! *) ... else ...

Introduction to Functional Programming Using OCaml 24 / 50

slide-25
SLIDE 25

Mutable Records

record fields can be mutable type complex = { mutable re: float; im: float; } let x = { re = 0.; im = 10. } in x.re ← 5.; x.im ← 15.; (* type error: im is not mutable *)

Introduction to Functional Programming Using OCaml 25 / 50

slide-26
SLIDE 26

References Are Mutable Records

type ’a ref = { mutable contents: ’a; } let make_ref x = { contents = x } let get x = x.contents let set x y = x.contents ← y let x = make_ref 0 in set x (get x + 5) (* x := !x + 5 *)

Introduction to Functional Programming Using OCaml 26 / 50

slide-27
SLIDE 27

While Loops

compute 10

i=1i with a while loop

let i = ref 1 in let sum = ref 0 in while !i <= 10 do sum := !sum + !i; i := !i + 1 done

Introduction to Functional Programming Using OCaml 27 / 50

slide-28
SLIDE 28

For Loops

compute 10

i=1i with a for loop

let sum = ref 0 in for i = 1 to 10 do sum := !sum + i done

Introduction to Functional Programming Using OCaml 28 / 50

slide-29
SLIDE 29

Issues With Side-Effects: Aliasing

let x = ref 0 in let y = x in x := 5; what is the value of !y ? = ⇒ side-effects make it harder to reason about your program

Introduction to Functional Programming Using OCaml 29 / 50

slide-30
SLIDE 30

Issues With Side-Effects: Concurrency

let x = ref 0 in x := 5; what is the value of !x if other programs can assign x at any time? = ⇒ side-effects are dangerous in the context of concurrency

Introduction to Functional Programming Using OCaml 30 / 50

slide-31
SLIDE 31

Issues With Side-Effects: Not “Mathematical”

let i = ref 1 in let sum = ref 0 in while !i <= 10 do sum := !sum + !i; i := !i + 1 done this is far from the mathematical definition of 10

i=1i

= ⇒ side-effects make it harder to reason about your program

Introduction to Functional Programming Using OCaml 31 / 50

slide-32
SLIDE 32

let’s talk about

functional programming

Introduction to Functional Programming Using OCaml 32 / 50

slide-33
SLIDE 33

Functional Programming

the functional programming paradigm:

◮ no side-effects (i.e. pure programs) ◮ strict but rich type system ◮ no goto (gotos are evil) ◮ functions are values

brings the programming language closer to mathematics

Introduction to Functional Programming Using OCaml 33 / 50

slide-34
SLIDE 34

Loops Are Recursive Functions

compute n

i=1i using the functional approach

let rec sum n = if n <= 0 then else n + sum (n - 1)

Introduction to Functional Programming Using OCaml 34 / 50

slide-35
SLIDE 35

Loops Are Recursive Functions

compute n

i=1i using the functional approach, again

let rec sum_aux acc n = if n <= 0 then acc else sum_aux (acc + n) (n - 1) let sum n = sum_aux 0 n

Introduction to Functional Programming Using OCaml 35 / 50

slide-36
SLIDE 36

Partial Application

let sum n = sum_aux 0 n is equivalent to let sum = sum_aux 0

Introduction to Functional Programming Using OCaml 36 / 50

slide-37
SLIDE 37

The Type of Functions

let add a b = a + b type of function add is int → int → int (read as int → (int → int)) function taking an integer argument a and returning another function taking an integer argument b and returning integer a + b

Introduction to Functional Programming Using OCaml 37 / 50

slide-38
SLIDE 38

The Type of Functions and Partial Application

example: partial application of function add let f = add 5 type of function f is int → int function taking an integer argument b and returning integer 5 + b

Introduction to Functional Programming Using OCaml 38 / 50

slide-39
SLIDE 39

Functions Are Values

let add a b = a + b is actually the same as: let add a = fun b → a + b

  • r as:

let add = fun a → fun b → a + b

Introduction to Functional Programming Using OCaml 39 / 50

slide-40
SLIDE 40

Functions as Arguments

functions can be given as arguments to other functions let f (g: int → int) (x: int): int = g x + 10 let n = f (add 5) 3 let m = f (fun x → 2 * x) 3 what is the value of n and m?

Introduction to Functional Programming Using OCaml 40 / 50

slide-41
SLIDE 41

Iterator: List Mapping

let rec map (f: ’a → ’b) (l: ’a list): ’b list = match l with | [] → [] | x :: rem → f x :: map f rem let x = map (add 5) [ 1; 2; 3 ] let y = map orbital_of_atom [ H | N | Be | Li ] what is the value of x and y?

Introduction to Functional Programming Using OCaml 41 / 50

slide-42
SLIDE 42

Iterator: List Folding

let rec fold (f: ’a → ’b → ’a) (a: ’a) (l: ’a list): ’b list = match l with | [] → a | x :: rem → fold f (f a x) rem let x = fold add 0 [ 1; 2; 3 ] what is the value of x?

Introduction to Functional Programming Using OCaml 42 / 50

slide-43
SLIDE 43

Example: Sum

compute n

i=1i using the functional approach, again again

let rec make_list n = if n <= 0 then [] else n :: make_list (n - 1) let sum n = fold add 0 (make_list n)

Introduction to Functional Programming Using OCaml 43 / 50

slide-44
SLIDE 44

Combinator: Function Composition

let compose f g x = f (g x) compute n

i=1i using the functional approach, again again again

let sum = compose (fold add 0) make_list = ⇒ good combination properties

Introduction to Functional Programming Using OCaml 44 / 50

slide-45
SLIDE 45

Matrix Product

recipe for a modular matrix product:

  • 1. write a function which returns the product of two matrices
  • 2. replace the use of * with a function argument
  • 3. enjoy a more general polymorph product function

apply it to:

◮ integer multiplication * for integer matrices ◮ float multiplication *. for float matrices ◮ other operators for other algebras

Introduction to Functional Programming Using OCaml 45 / 50

slide-46
SLIDE 46

Functional Programming: Conclusion

functional programming matters

◮ modular ◮ good compositional properties ◮ closer to a well-known language: mathematics ◮ less error-prone

Introduction to Functional Programming Using OCaml 46 / 50

slide-47
SLIDE 47

let’s talk about

numeric computation

Introduction to Functional Programming Using OCaml 47 / 50

slide-48
SLIDE 48

OCaml and Numeric Computation

available libraries for OCaml (standard library):

◮ various integers

◮ int

31 bits (32-bits processors) or 63 bits (64-bits processors) default integers of OCaml, fast

◮ int32, int64

less efficient, but one more bit

◮ arbitrary precision integers (modules Num and Big_int)

◮ floats

native floats, fast under some conditions

◮ large arrays (module Bigarray) of various integers and floats;

any dimension (vectors, 2D matrices, 3D matrices, and more); compatible with FORTRAN matrices bindings for libraries of other languages (including FORTRAN) may be written; some may already exist

Introduction to Functional Programming Using OCaml 48 / 50

slide-49
SLIDE 49

Conclusion

should you use OCaml? pros:

◮ less error-prone ◮ concise ◮ expressive (algebraic types, objects, modules and functors,

labels, polymorphic variants)

◮ scalable (modular, compositional) ◮ maintainable ◮ fast to compile ◮ fast to execute

cons:

◮ young (less available libraries and tools)

Introduction to Functional Programming Using OCaml 49 / 50

slide-50
SLIDE 50

References That Might, or Might Not, Be of Interest

OCaml website (download, documentation, community contents) http://caml.inria.fr/ John Hughes Why Functional Programming Matters Emmanuel Chailloux, Pascal Manoury and Bruno Pagano Developing Applications With Objective Caml Guy Cousineau and Michel Mauny The Functional Approach to Programming Jon D. Harrop OCaml for Scientists

Introduction to Functional Programming Using OCaml 50 / 50