From 05487b497d2893572fb2195209a3a8273d5de4bb Mon Sep 17 00:00:00 2001 From: giles Date: Sat, 9 May 2026 12:52:55 +0000 Subject: [PATCH] ocaml: phase 5.1 base_n.ml baseline (int to base-N string, length sum = 17) 36-character digit alphabet '0..9A..Z' supports any base 2..36. Loop divides the magnitude by base and prepends the digit: while !m > 0 do acc := String.make 1 digits.[!m mod base] ^ !acc; m := !m / base done Special-cases n = 0 -> '0' and prepends '-' for negatives. Test cases (length, since the strings differ in alphabet): 255 hex 'FF' 2 1024 binary '10000000000' 11 100 dec '100' 3 0 any base '0' 1 sum 17 Combines digits.[i] (string indexing) + String.make 1 ch + String concatenation in a loop. 61 baseline programs total. --- lib/ocaml/baseline/base_n.ml | 19 +++++++++++++++++++ lib/ocaml/baseline/expected.json | 1 + plans/ocaml-on-sx.md | 10 ++++++++++ 3 files changed, 30 insertions(+) create mode 100644 lib/ocaml/baseline/base_n.ml diff --git a/lib/ocaml/baseline/base_n.ml b/lib/ocaml/baseline/base_n.ml new file mode 100644 index 00000000..f3edb209 --- /dev/null +++ b/lib/ocaml/baseline/base_n.ml @@ -0,0 +1,19 @@ +let to_base_n n base = + let digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" in + if n = 0 then "0" + else begin + let m = ref (abs n) in + let acc = ref "" in + while !m > 0 do + acc := String.make 1 digits.[!m mod base] ^ !acc; + m := !m / base + done; + if n < 0 then "-" ^ !acc else !acc + end + +;; + +String.length (to_base_n 255 16) + +String.length (to_base_n 1024 2) + +String.length (to_base_n 100 10) + +String.length (to_base_n 0 16) diff --git a/lib/ocaml/baseline/expected.json b/lib/ocaml/baseline/expected.json index 12d1d880..3678a818 100644 --- a/lib/ocaml/baseline/expected.json +++ b/lib/ocaml/baseline/expected.json @@ -8,6 +8,7 @@ "bigint_add.ml": 28, "bits.ml": 21, "balance.ml": 3, + "base_n.ml": 17, "bfs.ml": 6, "btree.ml": 39, "brainfuck.ml": 75, diff --git a/plans/ocaml-on-sx.md b/plans/ocaml-on-sx.md index 1cd88fe1..bad1dfe8 100644 --- a/plans/ocaml-on-sx.md +++ b/plans/ocaml-on-sx.md @@ -407,6 +407,16 @@ _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 — base_n.ml baseline (int -> base-N string, + length sum 2+11+3+1 = 17). 36-character digit alphabet supports up + to base 36. Loop divides quotient by base, prepends digit. Tests: + 255 hex "FF" 2 + 1024 binary "10000000000" 11 + 100 dec "100" 3 + 0 any base "0" 1 + Sum 17. Combines digits.[!m mod base] (string indexing) + + String.make 1 ch (1-char string from 1-char string in our model) + + String concatenation in a loop. 61 baseline programs total. - 2026-05-09 Phase 5.1 — prime_factors.ml baseline (trial-division factorisation, sum of factors of 360 = 17). Three refs threading through a while loop: m holds the remaining quotient, d the