ocaml: phase 5.1 zerosafe.ml baseline (Option-chained safe division, sum = 28)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 24s
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 24s
safe_div returns None on division by zero; safe_chain stitches two
divisions, propagating None on either failure:
let safe_div a b =
if b = 0 then None else Some (a / b)
let safe_chain a b c =
match safe_div a b with
| None -> None
| Some q -> safe_div q c
Test:
safe_chain 100 2 5 = Some 10
safe_chain 100 0 5 = None -> -1
safe_chain 50 5 0 = None -> -1
safe_chain 1000 10 5 = Some 20
10 - 1 - 1 + 20 = 28
Tests Option chaining + match-on-result with sentinel default.
Demonstrates the canonical 'fail-early on None' pattern.
129 baseline programs total.
This commit is contained in:
@@ -118,6 +118,7 @@
|
||||
"tic_tac_toe.ml": 1,
|
||||
"word_freq.ml": 8,
|
||||
"xor_cipher.ml": 601,
|
||||
"zerosafe.ml": 28,
|
||||
"zigzag.ml": 55,
|
||||
"zip_unzip.ml": 1000,
|
||||
"sieve.ml": 15,
|
||||
|
||||
14
lib/ocaml/baseline/zerosafe.ml
Normal file
14
lib/ocaml/baseline/zerosafe.ml
Normal file
@@ -0,0 +1,14 @@
|
||||
let safe_div a b =
|
||||
if b = 0 then None else Some (a / b)
|
||||
|
||||
let safe_chain a b c =
|
||||
match safe_div a b with
|
||||
| None -> None
|
||||
| Some q -> safe_div q c
|
||||
|
||||
;;
|
||||
|
||||
(match safe_chain 100 2 5 with Some x -> x | None -> -1)
|
||||
+ (match safe_chain 100 0 5 with Some x -> x | None -> -1)
|
||||
+ (match safe_chain 50 5 0 with Some x -> x | None -> -1)
|
||||
+ (match safe_chain 1000 10 5 with Some x -> x | None -> -1)
|
||||
Reference in New Issue
Block a user