Files
rose-ash/lib/ocaml/baseline/validate.ml
giles 1a828d5b9f
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 23s
ocaml: phase 5.1 validate.ml baseline (Either-based validation, 3 errs * 100 + 117 = 417)
validate_int returns Left msg on empty / non-digit, Right
(int_of_string s) on a digit-only string. process folds inputs with a
tuple accumulator (errs, sum), branching on the result.

  ['12'; 'abc'; '5'; ''; '100'; 'x']
  -> 3 errors (abc, '', x), valid sum = 12+5+100 = 117
  -> errs * 100 + sum = 417

Exercises:
  - Either constructors used bare (Left/Right without 'Either.'
    qualification)
  - char range comparison: c >= '0' && c <= '9'
  - tuple-pattern destructuring on let-binding (iter 98)
  - recursive helper defined inside if-else
  - List.fold_left with tuple accumulator

36 baseline programs total.
2026-05-09 08:11:07 +00:00

25 lines
605 B
OCaml

let validate_int s =
if String.length s = 0 then Left "empty"
else
let rec all_digits i =
if i >= String.length s then true
else
let c = s.[i] in
if c >= '0' && c <= '9' then all_digits (i + 1)
else false
in
if all_digits 0 then Right (int_of_string s)
else Left ("not a number: " ^ s)
let process inputs =
List.fold_left (fun (errs, vals) s ->
match validate_int s with
| Left _ -> (errs + 1, vals)
| Right v -> (errs, vals + v)
) (0, 0) inputs
;;
let (errs, sum) = process ["12"; "abc"; "5"; ""; "100"; "x"] in
errs * 100 + sum