123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125(*
* Ref - Operations on references
* Copyright (C) 2008 David Teller
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version,
* with the special exception on linking described in file LICENSE.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)type'at='arefletpostrf=let old=!rinr:=fold;oldletprerf=r:=f!r;!rletswapab=letbuf=!aina:=!b;b:=buf(*$Tswap
let a = ref 1 and b = ref 2 in swap a b; !a = 2 && !b = 1
*)letpre_incrr=prer((+)1)letpre_decrr=prer((+)(-1))letpost_incrr=postr((+)1)letpost_decrr=postr((+)(-1))(*$T pre_incr
let r = ref 0 in pre_incr r = 1 && !r = 1
*)(*$T post_incr
let r = ref 0 in post_incr r = 0 && !r = 1
*)letcopyr=ref(!r)(*$T copy
letr = ref 0 in let s = copy r in r := 1; !s == 0 && !r == 1
*)letprotectrvbody=letold=!rintryr:=v;letres=body()inr:= old;reswithx->r:= old;raisex(*$T protect
let r = ref 0 in let b () = incr r; !r in protect r 2 b = 3 && !r = 0
let r = ref 0 in let b () = incr r; if !r=3 then raise Not_found in (try protect r 2 b; false with Not_found -> true) && !r = 0
*)externalref:'a->'aref="%makemutable"(** Return a fresh reference containing the given value. *)external(!):'aref->'a="%field0"(** [!r] returns the current contents of reference [r].
Equivalent to [fun r -> r.contents]. *)external(:=):'aref->'a->unit="%setfield0"(** [r := a] stores the value of [a] in reference [r].
Equivalent to [fun r v -> r.contents <- v]. *)externalset:'aref->'a->unit="%setfield0"(** As [ := ] *)externalget:'aref->'a="%field0"(** As [ ! ]*)letprintprint_aoutr=print_a out!rlettoggler=r:=not!r(*$T toggle
letr = ref true in toggle r; !r = false
let r = ref false in toggle r; !r = true
*)letosetrx=r:=Somexletoget_exnr=match!rwithNone ->raiseNot_found|Somex->x(* FAIL $T oset,oget_exn
let r = ref None in oset r 3; oget_exn r = 3
*)letcomparecxy=c!x!y(*$Tcompareleta = ref 1 and b = ref 2 in compare Int.compare a b < 0
*)letordoxy=o!x!y(*$Tord let a =ref 1 and b = ref 2 in ord Int.ord a b = BatOrd.Lt
*)leteqexy=e!x!y(*$Teq let a = ref 1 and b = ref 2 in eq Int.equal a b = false
let a = ref 1 and b = ref 1 in eq Int.equal a b = true
*)