Mutating is inevitable
It makes things efficient
int count = 0;
int new_num(){
return count++;
}
How to do in immutable data language?
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
let count = ref 0
let new_num () = let res = !count in
count := !count + 1;
res
Like a pointer
deref with !
update with :=
let count = ref 0
let new_num () = let res = !count in
count := !count + 1;
res
Seperate statements with ;
No different than a let expresion
let count = ref 0
let new_num () = let res = !count in
count := !count + 1;
res
Functions with () delay execution
Functions with references are confusing
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
Mutating is inevitable
it makes things efficient,
Hard to reason about
Order of evaluation now matters (in OCaml)
[new_num ();new_num (); new_num ()]
Order of evaluation now matters (in OCaml)
let y = ref 1;;
let f _ z = z+1;;
let w = f (y:=2) !y;;
w;;
Argument evaluation is unspecified in ocaml docs
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
Mutating is inevitable
it makes things efficient,
Data Structures are always changing
Arrays can be mutable
let arr = [|1;2;3|]
arr.(2) <- -3
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
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