ocaml-pure-polyrecord / test.ml

(* Record creation 

   {< .. >} is a record but all the fields are immutable.
   If you want to have mutability, use ref explicitly.
*)

let r = {< x = 1; y = ref None >}

(* Record access

   r..field

*)

let () = match r..x + 2 with 3 -> prerr_endline "ok" | _ -> assert false

(* Non existent field access is statically rejected.

let z = r..z

*)

(* You can define polymorphic accessor, however. *)

let get_z r = r..z

let get_z_w r = r..z..w

(* Marshalling. Those records are just hashtbls, so streamable *)

let () = output_value stdout r; print_newline ()

(* Making a copy with 

   {< r with bindings >}

*)

let r2 = {< r with x = 3 >}

(* You cannot add fields at copy. :-(

   let r2 = {< r with z = 3 >} 

*)

(* You can forget fields via explicit coercion *)

let r3 = (r2 :> < x : int > Polyrecord.t)

(* Mutability via ref member by 

   r..field <- e

*)

let () = r2..y <- Some 3;; 

(* Mutable field cannot have poly type

   let () = r2..y <- Some 3.0 (* error *)
*)

(* Accessing the content of the mutable field is via (!).
   A bit glitchy... 
*)

let () = Printf.printf "%d\n" (match !(r2..y) with None -> -1 | Some v -> v)

(* !r..y = (!r)..y  not  !(r..y)

   just like !r.y = (!r).y  not  !(r.y)

*)

let g r = !r..y
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.