Module Bonsai.Dynamic_scope

This module implements dynamic variable scoping. Once a dynamic variable is created, you can store values in it, and lookup those same values. A lookup will find the nearest-most parent "unreverted" set call where a "set" can be "reverted" with set''s revert.

type 'a bonsai_t := 'a t
type 'a t
val create : ?sexp_of:('a -> Core.Sexp.t) -> name:string -> fallback:'a -> unit -> 'a t

Creates a new variable for use with the rest of the functions. It is critically important that the exact same Dynamic_scope.t is used in calls to set and the corresponding lookup.

val derived : ?sexp_of:('a -> Core.Sexp.t) -> 'b t -> get:('b -> 'a) -> set:('b -> 'a -> 'b) -> 'a t

Creates a variable which is derived from another. Typically this is used to project out a field of another dynamic variable which contains a record.

val set : here:lexing_position -> 'a t -> 'a bonsai_t -> inside:(graph @ local -> 'r bonsai_t) -> graph @ local -> 'r bonsai_t

Given a 'a Dynamic_scope.t and a 'a Bonsai.t evaluate the ~inside function that now has access to the value via the lookup function.

type revert = {
  1. revert : 'a. (graph @ local -> 'a bonsai_t) -> graph @ local -> 'a bonsai_t;
}
val set' : here:lexing_position -> 'a t -> 'a bonsai_t -> f:(revert -> graph @ local -> 'r bonsai_t) -> graph @ local -> 'r bonsai_t

like set but with the ability to revert the value in sub-computations.

val lookup : here:lexing_position -> 'a t -> graph @ local -> 'a bonsai_t

Lookup attempts to find the value inside the nearest scope, but if there isn't one, it falls back to default specified in create.

val modify : here:lexing_position -> 'a t -> change:('a bonsai_t -> 'a bonsai_t) -> f:(revert -> graph @ local -> 'r bonsai_t) -> graph @ local -> 'r bonsai_t

modify can be used to change the current value of a dynamically scoped variable.