From 095bb62ef91a21873e1da48affe28cc62e21a98f Mon Sep 17 00:00:00 2001 From: giles Date: Sat, 9 May 2026 08:39:56 +0000 Subject: [PATCH] ocaml: phase 5.1 rpn.ml baseline (Reverse Polish Notation evaluator, [3 4 + 2 * 5 -] = 9) Stack-based RPN evaluator: let eval_rpn tokens = let stack = Stack.create () in List.iter (fun tok -> if tok is operator then let b = Stack.pop stack in let a = Stack.pop stack in Stack.push (apply tok a b) stack else Stack.push (int_of_string tok) stack ) tokens; Stack.pop stack For tokens [3 4 + 2 * 5 -]: 3 4 + -> 7 7 2 * -> 14 14 5 - -> 9 Exercises Stack.create / push / pop, mixed branch on string equality, multi-arm if/else if for operator dispatch, int_of_string for token parsing. 39 baseline programs total. --- lib/ocaml/baseline/expected.json | 1 + lib/ocaml/baseline/rpn.ml | 20 ++++++++++++++++++++ plans/ocaml-on-sx.md | 7 +++++++ 3 files changed, 28 insertions(+) create mode 100644 lib/ocaml/baseline/rpn.ml diff --git a/lib/ocaml/baseline/expected.json b/lib/ocaml/baseline/expected.json index a11b46ce..f2f5b5c2 100644 --- a/lib/ocaml/baseline/expected.json +++ b/lib/ocaml/baseline/expected.json @@ -31,6 +31,7 @@ "queens.ml": 2, "quicksort.ml": 44, "roman.ml": 44, + "rpn.ml": 9, "safe_div.ml": 20, "shuffle.ml": 55, "word_freq.ml": 8, diff --git a/lib/ocaml/baseline/rpn.ml b/lib/ocaml/baseline/rpn.ml new file mode 100644 index 00000000..d2fc7e94 --- /dev/null +++ b/lib/ocaml/baseline/rpn.ml @@ -0,0 +1,20 @@ +let eval_rpn tokens = + let stack = Stack.create () in + List.iter (fun tok -> + if tok = "+" || tok = "-" || tok = "*" || tok = "/" then begin + let b = Stack.pop stack in + let a = Stack.pop stack in + let r = if tok = "+" then a + b + else if tok = "-" then a - b + else if tok = "*" then a * b + else a / b + in + Stack.push r stack + end else + Stack.push (int_of_string tok) stack + ) tokens; + Stack.pop stack + +;; + +eval_rpn ["3"; "4"; "+"; "2"; "*"; "5"; "-"] diff --git a/plans/ocaml-on-sx.md b/plans/ocaml-on-sx.md index f9651bcc..a5c1e94f 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 — rpn.ml baseline (Reverse Polish Notation + evaluator using Stack). Walks the token list with List.iter, pushes + ints onto the stack, on operator tokens pops two operands and + pushes the result. `[3 4 + 2 * 5 -]` evaluates as 3+4=7, 7*2=14, + 14-5=9 → 9. Exercises Stack.create / push / pop, mixed branch on + string equality, multi-arm if/else if, int_of_string for token + parsing. 39 baseline programs total. - 2026-05-09 Phase 5.1 — newton_sqrt.ml baseline (Newton's method for sqrt, sqrt(2)*1000 truncated → 1414). 20 iterations of `g := (g + x/g) / 2` converges to ~1.414213562 for x=2. Multiplied