ocaml: phase 5.1 peano.ml baseline (Peano arithmetic, 5*6 = 30)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 25s

Defines unary Peano numerals with two recursive functions for
arithmetic:

  type peano = Zero | Succ of peano

  let rec plus a b = match a with
    | Zero -> b
    | Succ a' -> Succ (plus a' b)

  let rec mul a b = match a with
    | Zero -> Zero
    | Succ a' -> plus b (mul a' b)

mul is defined inductively: mul Zero _ = Zero; mul (Succ a) b =
b + (a * b).

  to_int (mul (from_int 5) (from_int 6)) = 30

The result is a Peano value with 30 nested Succ wrappers; to_int
unrolls them to a host int. Tests recursive ADT with a single-arg
constructor + four mutually-defined recursive functions (no rec/and
needed since each is defined separately).

80 baseline programs total — milestone.
This commit is contained in:
2026-05-09 16:38:09 +00:00
parent 2129e04bfd
commit b7b841821c
3 changed files with 30 additions and 0 deletions

View File

@@ -56,6 +56,7 @@
"paren_depth.ml": 7,
"pancake_sort.ml": 910,
"pascal.ml": 252,
"peano.ml": 30,
"pi_leibniz.ml": 314,
"prefix_sum.ml": 66,
"pretty_table.ml": 64,

View File

@@ -0,0 +1,21 @@
type peano = Zero | Succ of peano
let rec to_int p = match p with
| Zero -> 0
| Succ p' -> 1 + to_int p'
let rec from_int n =
if n = 0 then Zero
else Succ (from_int (n - 1))
let rec plus a b = match a with
| Zero -> b
| Succ a' -> Succ (plus a' b)
let rec mul a b = match a with
| Zero -> Zero
| Succ a' -> plus b (mul a' b)
;;
to_int (mul (from_int 5) (from_int 6))