From acc8b01ddbab08656fcce3a0cb29e8ff319ebfc5 Mon Sep 17 00:00:00 2001 From: giles Date: Sat, 9 May 2026 12:04:42 +0000 Subject: [PATCH] ocaml: phase 5.1 exception_user.ml baseline (user exception with payload, 4+5+7+10 = 26) Defines a user exception with int payload: exception Negative of int let safe_sqrt n = if n < 0 then raise (Negative n) else let try_sqrt n = try safe_sqrt n with | Negative x -> -x try_sqrt 16 -> 4 try_sqrt 25 -> 5 try_sqrt -7 -> 7 (handler returns -(-7) = 7) try_sqrt 100 -> 10 sum -> 26 Tests exception declaration with int payload, raise with carry, and try-with arm pattern-matching the constructor with payload binding. 56 baseline programs total. --- lib/ocaml/baseline/exception_user.ml | 16 ++++++++++++++++ lib/ocaml/baseline/expected.json | 1 + plans/ocaml-on-sx.md | 7 +++++++ 3 files changed, 24 insertions(+) create mode 100644 lib/ocaml/baseline/exception_user.ml diff --git a/lib/ocaml/baseline/exception_user.ml b/lib/ocaml/baseline/exception_user.ml new file mode 100644 index 00000000..1b00455a --- /dev/null +++ b/lib/ocaml/baseline/exception_user.ml @@ -0,0 +1,16 @@ +exception Negative of int + +let safe_sqrt n = + if n < 0 then raise (Negative n) + else + let g = ref 1 in + while !g * !g < n do g := !g + 1 done; + !g + +let try_sqrt n = + try safe_sqrt n with + | Negative x -> -x + +;; + +try_sqrt 16 + try_sqrt 25 + try_sqrt (-7) + try_sqrt 100 diff --git a/lib/ocaml/baseline/expected.json b/lib/ocaml/baseline/expected.json index 037e7084..bb5b75fe 100644 --- a/lib/ocaml/baseline/expected.json +++ b/lib/ocaml/baseline/expected.json @@ -15,6 +15,7 @@ "coin_change.ml": 6, "csv.ml": 10, "exception_handle.ml": 4, + "exception_user.ml": 26, "expr_eval.ml": 16, "expr_simp.ml": 22, "factorial.ml": 3628800, diff --git a/plans/ocaml-on-sx.md b/plans/ocaml-on-sx.md index e185bb34..adcdbb15 100644 --- a/plans/ocaml-on-sx.md +++ b/plans/ocaml-on-sx.md @@ -407,6 +407,13 @@ _Newest first._ binary search tree (`type 'a tree = Leaf | Node of 'a * 'a tree * 'a tree`) with insert + in-order traversal. Tests parametric ADT, recursive match, List.append, List.fold_left. +- 2026-05-09 Phase 5.1 — exception_user.ml baseline (user-defined + exception with int payload, 4+5+7+10 = 26). Defines `exception + Negative of int`, `safe_sqrt` raises it on negative input, and + `try_sqrt` catches with `try ... with | Negative x -> -x`. Tests + exception declaration, raise with carry-payload, try-with arm + matching the constructor and binding the payload. 56 baseline + programs total. - 2026-05-09 Phase 5.1 — flatten_tree.ml baseline (parametric ADT flatten, sum 1..7 = 28). Defines `type 'a tree = Leaf of 'a | Node of 'a tree list` then `flatten` recursively expands using