CMSC330

Ocaml

OCaml

References
Side Effects
The other stuff

References

Mutating is inevitable

It makes things efficient


int count = 0;

int new_num(){
  return count++;
}
          

How to do in immutable data language?

References


int count = 0;

int new_num(){
  return count++;
}
          

How to do in immutable data language?


let count = ref 0

let new_num () = let res = !count in 
                 count := !count + 1;
                 res
          

References


let count = ref 0

let new_num () = let res = !count in 
                 count := !count + 1;
                 res
          

Like a pointer

deref with !

update with :=

References


let count = ref 0

let new_num () = let res = !count in 
                 count := !count + 1;
                 res
          

Seperate statements with ;

No different than a let expresion

References


let count = ref 0

let new_num () = let res = !count in 
                 count := !count + 1;
                 res
          

Functions with () delay execution

Functions with references are confusing

References

Functions with references are confusing


let new_num = let count = ref 0 in 
                 fun () -> 
                 let res = !count in 
                 count := !count + 1;
                 res
          

Closure has ref, and fun

Side Effects

Mutating is inevitable

it makes things efficient,

Hard to reason about

Order of evaluation now matters (in OCaml)


[new_num ();new_num (); new_num ()]
          

The Other stuff

Mutating is inevitable

it makes things efficient,

Data Structures are always changing

Records can be mutable


type user = {name:string; mutable age:int}
let clyff = {name="clyff"; age=47}
clyff.age <- 74
          

The Other stuff

Mutating is inevitable

it makes things efficient,

Data Structures are always changing

Arrays can be mutable


let arr = [|1;2;3]|
arr.(2) <- -3
          

The Other stuff

Mutating is inevitable

it makes things efficient,

Looping is actually in OCaml


while true do print_string "I never end\n" done
for x=0 to 0 do print_int x; print_string "\n" done
for x=5 downto 0 do print_int x; print_string "\n" done
          

The Other stuff

Mutating is inevitable

it makes things efficient,

Hash Tables are very common


            let ht = Hashtbl.create 10
            Hashtbl.add ht "key" "value"
            Hashtbl.find ht "key"
            Hashtbl.iter (fun k v -> print_string ("Key: " ^ k ^ 
                                     "\tValue:" ^ v)) ht