Bigger Example
Resources: OMAP Incremental Jane Street GitHub Docs
Here is an example in utop…
Setup
#require "core";;
#require "incremental";;
open Core;;
module Inc = Incremental.Make ();;
module Var = Inc.Var;;Example 1
1let inputs = Array.init 100_000 ~f:(fun _ -> Inc.Var.create 0.);;
2
3let incr_list_sum l =
4match List.reduce_balanced l ~f:(Inc.map2 ~f:( +. )) with
5| None -> Var.watch (Var.create 0.)
6| Some x -> x;;
7
8let sum =
9List.map ~f:Inc.Var.watch (Array.to_list inputs)
10|> incr_list_sum
11|> Inc.observe;;
12
13
14Inc.stabilize ();;
15
16Inc.Observer.value_exn sum;;- : float = 0.1let incr i x = Inc.Var.set inputs.(i) (Inc.Var.value inputs.(i) +. x) in
2incr 100 1.6;
3incr 72 0.2;
4incr 105 0.4;
5Inc.stabilize ();;
6
7Inc.Observer.value_exn sum;;- : float = 2.2Projections and Cutoffs
Reference: deriving fields ~getters
Additional setup for using Let_syntax…
1#require "ppx_jane";;
2open Inc.Let_syntax;; 1type z =
2{ a: int list
3; b: (int * int)
4};;
5(* [@@deriving fields ~getters] ;; *)
6
7let sumproduct z =
8 let a_prod =
9 let%map a = z >>| (fun (d:z) -> d.a ) in
10 printf "a\n";
11 List.fold ~init:1 ~f:( * ) a
12 in
13 let b_prod =
14 let%map (b1,b2) = z >>| (fun (d:z) -> d.b ) in
15 printf "b\n";
16 b1 * b2
17 in
18 let%map a_prod = a_prod and b_prod = b_prod in
19 a_prod + b_prod
20;;
21
22let q = Inc.Var.create { a = [3;2]; b = (1,4) };;
23
24let result = Inc.observe (sumproduct (Inc.Var.watch q));;
25
26let show () =
27 Inc.stabilize ();
28 printf "result: %d\n" (Inc.Observer.value_exn result);;
29
30let () = show ();;b
a
result: 101let () =
2Inc.Var.set q { (Inc.Var.value q) with b = (1,1) };
3show ();;b
result: 7