Download Introduction to Programming in Objective Caml: A Functional Language - Prof. Jeffrey S. Fo and more Study notes Computer Science in PDF only on Docsity!
CMSC 631 ā Program Analysis and
Understanding
Spring 2009
Functional Programming with OCaml
2
Background
⢠ML (Meta Language)
ā Univ. of Edinburgh, 1973
ā Part of a theorem proving system LCF
- The Logic of Computable Functions
⢠SML/NJ (Standard ML of New Jersey)
ā Bell Labs and Princeton, 1990
ā Now Yale, AT&T Research, Univ. of Chicago (among
others)
⢠OCaml (Objective CAML)
ā INRIA, 1996
ā French NatālInstitute for Research in Computer Science
Dialects of ML
⢠Other dialects include MoscowML, ML Kit,
Concurrent ML, etc.
ā But SML/NJ and OCaml are most popular
ā O = āObjective,ā but probably wonāt cover objects
⢠Languages all have the same core ideas
ā But small and annoying syntactic differences
ā So you should not buy a book with ML in the title
- Because it probably wonāt cover OCaml
More Information on OCaml
⢠Translation available
on the class webpage
ā Developing
Applications with
Objective Caml
⢠Webpage also has link
to another book
ā Introduction to the
Objective Caml
Programming
Language
5
Features of ML
⢠Higher-order functions
- Functions can be parameters and return values
⢠āMostly functionalā
⢠Data types and pattern matching
- Convenient for certain kinds of data structures
⢠Type inference
- No need to write types in the source language
- But the language is statically typed
- Supports parametric polymorphism
- Generics in Java, templates in C++
⢠Exceptions
⢠Garbage collection
6
Functional languages
⢠In a pure functional language, every program is
just an expression evaluation
let add1 x = x + 1;;
let rec add (x,y) = if x=0 then y else add(x-1, add1(y));;
add(2,3) = add(1,add1(3)) = add(0,add1(add1(3)))
= add1(add1(3)) = add1(3+1) = 3+1+
OCaml has this basic behavior, but has additional
features to ease the programming process.
- Less emphasis on data storage
- More emphasis on function execution
A Small OCaml Program- Things to Notice
(* A small OCaml program *) let x = 37;; let y = x + 5;; print_int y;; print_string "\n";;
Use (* *) for comments (may nest)
;; ends a top-level expression
Use let to bind variables
No type declarations
Need to use correct print function
(OCaml also has printf)
Line breaks, spacing ignored (like
C, C++, Java, not like Ruby)
Run, OCaml, Run
⢠OCaml programs can be compiled using ocamlc
ā Produces .cmo (ācompiled objectā) and .cmi
(ācompiled interfaceā) files
- Weāll talk about interface files later
ā By default, also links to produce executable a.out
- Use -o to set output file name
- Use -c to compile only to .cmo/.cmi and not to link
- You'll be given a Makefile if you need to compile your files
13
More on the Let Construct
⢠let is more often used for local variables
ā let x = e1 in e2 means
- Evaluate e
- Then evaluate e2, with x bound to result of evaluating e
- x is not visible outside of e let pi = 3.14 in pi *. 3.0 *. 3.0;; pi;;
bind pi in body of let floating point multiplication
error
14
More on the Let Construct (contād)
⢠Compare to similar usage in Java/C
⢠In the top-level, omitting in means āfrom now onā:
# let pi = 3.14;;
(* pi is now bound in the rest of the top-level scope *)
let pi = 3.14 in pi *. 3.0 *. 3.0;; pi;; { float pi = 3.14; pi * 3.0 * 3.0; } pi;
Nested Let
⢠Uses of let can be nested
let pi = 3.14 in let r = 3.0 in pi *. r . r;; ( pi, r no longer in scope ) { float pi = 3.14; float r = 3.0; pi * r * r; } / pi, r not in scope */
Defining Functions
let next x = x + 1;; next 3;; let plus (x, y) = x + y;; plus (3, 4);;
use let to define functions
list parameters after function name
no parentheses on function calls^ no return statement
17
Local Variables
⢠You can use let inside of functions for locals
ā And you can use as many lets as you want
let area r = let pi = 3.14 in pi *. r *. r let area d = let pi = 3.14 in let r = d /. 2.0 in pi *. r *. r 18
Function Types
⢠In OCaml,^ ->^ is the function type constructor
ā The type^ t1 ->^ t2^ is a function with argument or
domain type t1 and return or range type t
⢠Examples
- let next x = x + 1 (* type int -> int *)
- let fn x = (float_of_int x) . 3. ( type int -> float *)
- print_string (* type string -> unit *)
⢠Type a function name at top level to get its type
Type Annotations
⢠The syntax^ (e^ : t)^ asserts that āe^ has type^ tā
ā This can be added anywhere you like
let (x : int) = 3 let z = (x : int) + 5
⢠Use to give functions parameter and return types
let fn (x:int):float = (float_of_int x) *. 3.
ā Note special position for return type
ā Thus let g x:int = ... means g returns int
⢠Very useful for debugging, especially for more
complicated types
;; versus ;
⢠;; ends an expression in the top-level of OCaml
ā Use it to say: āGive me the value of this expressionā
ā Not used in the body of a function
ā Not needed after each function definition
- Though for now it wonāt hurt if used there
⢠e1; e2 evaluates e1 and then e2, and returns e
let print_both (s, t) = print_string s; print_string t; "Printed s and t."
ā notice no ; at end---itās a separator , not a terminator
print_both (āColorless green ", āideas sleep")
Prints āColorless green ideas sleep", and returns
"Printed s and t."
25
More Examples
let y = [1;2;3] ;;
val y : int list = [1; 2; 3]
let x = 4::y ;;
val x : int list = [4; 1; 2; 3]
let z = 5::y ;;
val z : int list = [5; 1; 2; 3]
- not modifying existing lists, just creating new lists
let w = [1;2]::y ;;
This expression has type int list but is here used with type int list list
- The left argument of :: is an element
- Can you construct a list y such that [1;2]::y makes sense? 26
Lists of Lists
⢠Lists can be nested arbitrarily
ā Example: [ [9; 10; 11]; [5; 4; 3; 2] ]
Pattern Matching
⢠To pull lists apart, use the match construct
match e with p1 -> e1 | ... | pn -> en
⢠p1...pn are patterns made up of [], ::, and pattern
variables
⢠match finds the first pk that matches the shape of e
- Then^ ek^ is evaluated and returned
- During evaluation of pk, pattern variables in pk are bound to the corresponding parts of e
⢠An underscore _ is a wildcard pattern
- Matches anything
- Doesnāt add any bindings
- Useful when you want to know something matches, but donāt care what its value is
Example
match e with p1 -> e1 | ... | pn -> en let is_empty l = match l with [] -> true | (h::t) -> false is_empty [] (* evaluates to true ) is_empty [1] ( evaluates to false ) is_empty [1;2;3] ( evaluates to false *)
29
Pattern Matching (contād)
- let hd l = match l with (h::t) -> h
- hd [1;2;3] (* evaluates to 1 *)
- let hd l = match l with (h::_) -> h
- hd [] (* error! no pattern matches *)
- let tl l = match l with (h::t) -> t
- tl [1;2;3] (* evaluates to [2; 3] *) 30
Missing Cases
⢠Exceptions for inputs that donāt match any pattern
ā OCaml will warn you about non-exhaustive matches
⢠Example:
# let hd l = match l with (h::_) -> h;;
Warning: this pattern-matching is not exhaustive. Here is an example of a value that is not matched: []
hd [];;
Exception: Match_failure ("", 1, 11).
More Examples
- let f l = match l with (h1::(h2::_)) -> h1 + h
- f [1;2;3]
- (* evaluates to 3 *)
- let g l = match l with [h1; h2] -> h1 + h
- g [1; 2]
- (* evaluates to 3 *)
- g [1; 2; 3]
- (* error! no pattern matches *)
An Abbreviation
⢠let f p = e, where p is a pattern, is a
shorthand for let f x = match x with p -> e
⢠Examples
- let hd (h::_) = h
- let tl (_::t) = t
- let f (x::y::_) = x + y
- let g [x; y] = x + y
⢠Useful if thereās only one acceptable input
37
List and Tuple Types
⢠Tuple types use^ *^ to separate components
⢠Examples
- (1, "string", 3.5) :
- (1, ["a"; "b"], 'c') :
- [(1,2)] :
- [(1, 2); (3, 4)] :
- [(1,2); (1,2,3)] : 38
List and Tuple Types
⢠Tuple types use^ *^ to separate components
⢠Examples
- (1, 2) : int * int
- (1, "string", 3.5) : int * string * float
- (1, ["a"; "b"], 'c') : int * string list * char
- [(1,2)] : (int * int) list
- [(1, 2); (3, 4)] : (int * int) list
- [(1,2); (1,2,3)] : error
Type declarations
⢠type can be used to create new names for types
ā useful for combinations of lists and tuples
⢠Examples
type my_type = int * (int list) (3, [1; 2]) : my_type type my_type2 = int * char * (int * float) (3, āaā, (5, 3.0)) : my_type
Polymorphic Types
⢠Some functions we saw require specific list types
- let plusFirstTwo (x::y::_, a) = (x + a, y + a)
- plusFirstTwo : int list * int -> (int * int)
⢠But other functions work for any list
- let hd (h::_) = h
- hd [1; 2; 3] (* returns 1 *)
- hd ["a"; "b"; "c"] (* returns "a" *)
⢠OCaml gives such functions polymorphic types
ā this says the function takes a list of any element type
'a, and returns something of that type
41
Examples of Polymorphic Types
- let tl (_::t) = t
- let swap (x, y) = (y, x)
- swap : 'a * 'b -> 'b * 'a
- let tls (_::xs, _::ys) = (xs, ys)
- tls : 'a list * 'b list -> 'a list * 'b list 42
Tuples Are a Fixed Size
let foo x = match x with
(a, b) -> a + b | (a, b, c) -> a + b + c;; This pattern matches values of type 'a * 'b * 'c but is here used to match values of type 'd * 'e
⢠Thus there's never more than one match case
with tuples
Conditionals
⢠Use if...then...else just like C/Java
ā No parentheses and no end
if grade >= 90 then print_string "You got an A" else if grade >= 80 then print_string "You got a B" else if grade >= 70 then print_string "You got a C" else print_string "Youāre not doing so well"
Conditionals (contād)
⢠In OCaml, conditionals return a result
ā The value of whichever branch is true/false
ā Like? : in C, C++, and Java
if 7 > 42 then "hello" else "goodbye";;
let x = if true then 3 else 4;;
x : int = 3
if false then 3 else 3.0;;
This expression has type float but is here used with type int
⢠Putting this together with what weāve seen
earlier, can you write fact, the factorial function?
49
Lists and Recursion
⢠Lists have a recursive structure
ā And so most functions over lists will be recursive
ā This is just like an inductive definition
- The length of the empty list is zero
- The length of a nonempty list is 1 plus the length of the tail
ā Type of length?
let rec length l = match l with [] -> 0 | (_::t) -> 1 + (length t) 50
More Examples
- sum l (* sum of elts in l *) let rec sum l = match l with [] -> 0 | (x::xs) -> x + (sum xs)
- negate l (* negate elements in list *) let rec negate l = match l with [] -> [] | (x::xs) -> (-x) :: (negate xs)
- last l (* last element of l *) let rec last l = match l with [x] -> x | (x::xs) -> last xs
More Examples (contād)
(* return a list containing all the elements in the list l followed by all the elements in list m *)
- append (l, m) let rec append (l, m) = match l with [] -> m | (x::xs) -> x::(append (xs, m))
- rev l (* reverse list; hint: use append *) let rec rev l = match l with [] -> [] | (x::xs) -> append ((rev xs), [x])
⢠rev takes O(n^2 ) time. Can you do better?
A Clever Version of Reverse
let rec rev_helper (l, a) = match l with [] -> a | (x::xs) -> rev_helper (xs, (x::a)) let rev l = rev_helper (l, [])
⢠Letās give it a try
rev [1; 2; 3]! rev_helper ([1;2;3], [])! rev_helper ([2;3], [1])! rev_helper ([3], [2;1])! rev_helper ([], [3;2;1])! [3;2;1]
53
More Examples
- flattenPairs l (* ('a * 'a) list -> 'a list *) let rec flattenPairs l = match l with [] -> [] | ((a, b)::t) -> a :: b :: (flattenPairs t)
- take (n, l) (* return first n elts of l *) let rec take (n, l) = if n = 0 then [] else match l with [] -> [] | (x::xs) -> x :: (take (n-1, xs)) 54
Working with Lists
⢠Several of these examples have the same flavor
ā Walk through the list and do something to every element
ā Walk through the list and keep track of something
⢠Recall the following example code from Ruby:
ā Here we passed a code block into the collect method
ā Wouldnāt it be nice to do the same in OCaml?
a = [1,2,3,4,5] b = a.collect { |x| -x }
Higher-Order Functions
⢠In OCaml you can pass functions as arguments,
and return functions as results
let plus_three x = x + 3 let twice (f, z) = f (f z) twice (plus_three, 5) twice : ('a->'a) * 'a -> 'a let plus_four x = x + 4 let pick_fn n = if n > 0 then plus_three else plus_four (pick_fn 5) 0 pick_fn : int -> (int->int)
The map Function
⢠Letās write the map function (just like Ruby's collect)
ā Takes a function and a list, applies the function to each
element of the list, and returns a list of the results
let add_one x = x + 1 let negate x = -x map (add_one, [1; 2; 3]) map (negate, [9; -5; 0])
⢠Type of^ map?
let rec map (f, l) = match l with [] -> [] | (h::t) -> (f h)::(map (f, t))
61 let rec fold (f, a, l) = match l with [] -> a | (h::t) -> fold (f, f (a, h), t)
The fold Function
⢠Common pattern: iterate through a list and apply
a function to each element, keeping track of the
partial results computed so far
ā a = āaccumulatorā
ā this is usually called āfold leftā to remind us that f
takes the accumulator as its first argument
⢠What's the type of fold?
62
Example
let add (a, x) = a + x fold (add, 0, [1; 2; 3; 4])! fold (add, 1, [2; 3; 4])! fold (add, 3, [3; 4])! fold (add, 6, [4])! fold (add, 10, [])! 10
We just built the sum function!
let rec fold (f, a, l) = match l with [] -> a | (h::t) -> fold (f, f (a, h), t)
Another Example
let next (a, _) = a + 1 fold (next, 0, [2; 3; 4; 5])! fold (next, 1, [3; 4; 5])! fold (next, 2, [4; 5])! fold (next, 3, [5])! fold (next, 4, [])! 4
We just built the length function!
let rec fold (f, a, l) = match l with [] -> a | (h::t) -> fold (f, f (a, h), t)
Using fold to Build rev
⢠Can you build the reverse function with fold?
let prepend (a, x) = x::a fold (prepend, [], [1; 2; 3; 4])! fold (prepend, [1], [2; 3; 4])! fold (prepend, [2; 1], [3; 4])! fold (prepend, [3; 2; 1], [4])! fold (prepend, [4; 3; 2; 1], [])! [4; 3; 2; 1] let rec fold (f, a, l) = match l with [] -> a | (h::t) -> fold (f, f (a, h), t)
65
The Call Stack in C/Java/etc.
void f(void) { int x; x = g(3); }
x
int g(int x) { int y; y = h(x); return y; } int h (int z) { return z + 1; }
x 3
y
z 3
int main(){ f(); return 0; }
f
g
h
66
Nested Functions
⢠In OCaml, you can define functions anywhere
ā Even inside of other functions
let pick_one n = if n > 0 then (fun x -> x + 1) else (fun x -> x - 1) (pick_one -5) 6 (* returns 5 *) let sum l = fold ((fun (a, x) -> a + x), 0, l)
Nested Functions (contād)
⢠You can also use let to define functions inside of
other functions
let sum l = let add (a, x) = a + x in fold (add, 0, l) let pick_one n = let add_one x = x + 1 in let sub_one x = x - 1 in if n > 0 then add_one else sub_one
How About This?
ā (Equivalent to...)
let addN (n, l) = let add x = n + x in map (add, l)
Accessing variable
from outer scope
let addN (n, l) = map ((fun x -> n + x), l)
73
Example
let add x = (fun y -> x + y) (add 3) 4! 4! 3 + 4! 7 74
Another Example
let mult_sum (x, y) = let z = x + y in fun w -> w * z (mult_sum (3, 4)) 5! 5! 5 * 7! 35
Yet Another Example
let twice (n, y) = let f x = x + n in f (f y) twice (3, 4)! ( 4)! 7! 10
Still Another Example
let add x = (fun y -> (fun z -> x + y + z)) (((add 1) 2) 3)! (( 2) 3)! ( 3)! 1+2+
77
Currying
⢠We just saw another way for a function to take
multiple arguments
ā The function consumes one argument at a time,
creating closures until all the arguments are available
⢠This is called currying the function
ā Named after the logician Haskell B. Curry
ā But Schƶnfinkel and Frege discovered it
- So it should probably be called Schƶnfinkelizing or Fregging 78
Curried Functions in OCaml
⢠OCaml has a really simple syntax for currying
ā This is identical to all of the following:
⢠Thus:
ā add has type int -> (int -> int)
ā add 3 has type int -> int
- add 3 is a function that adds 3 to its argument
- (add 3) 4 = 7
⢠This works for any number of arguments
let add x y = x + y let add = (fun x -> (fun y -> x + y)) let add = (fun x y -> x + y) let add x = (fun y -> x+y)
Curried Functions in OCaml (contād)
⢠Because currying is so common, OCaml uses
the following conventions:
ā -> associates to the right
- Thus int -> int -> int is the same as
- int -> (int -> int)
ā function application associates to the left
- Thus^ add^3 4 is the same as
- (add 3) 4
Another Example of Currying
⢠A curried add function with three arguments:
ā The same as
⢠Then...
ā add_th has type int -> (int -> (int -> int))
ā add_th 4 has type int -> (int -> int)
ā add_th 4 5 has type int -> int
ā add_th 4 5 6 is 15
let add_th x y z = x + y + z let add_th x = (fun y -> (fun z -> x+y+z))