Chapter 8  Language extensions

This chapter describes language extensions and convenience features that are implemented in OCaml, but not described in the OCaml reference manual.

20  Extended indexing operators

(Introduced in 4.06)

dot-ext::=  
  (!∣ $∣ %∣ &∣ *∣ +∣ -∣ /∣ :∣ =∣ >∣ ?∣ @∣ ^∣ |∣ ~) { operator-char }  
 
expr::= ...  
  expr .  [module-path .]  dot-ext  ( ( expr ) ∣  [ expr ] ∣  { expr } )  [ <- expr ]  
 
operator-name::= ...  
  . dot-ext  (() ∣  [] ∣  {}) [<-]  
 

This extension provides syntactic sugar for getting and setting elements for user-defined indexed types. For instance, we can define python-like dictionaries with

module Dict = struct include Hashtbl let ( .%{} ) tabl index = find tabl index let ( .%{}<- ) tabl index value = add tabl index value end let dict = let dict = Dict.create 10 in let () = dict.Dict.%{"one"} <- 1; let open Dict in dict.%{"two"} <- 2 in dict
dict.Dict.%{"one"};;
- : int = 1
let open Dict in dict.%{"two"};;
- : int = 2