ocaml: phase 5.1 atm.ml baseline (mutable record + exception + try/with, balance = 120)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 34s
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 34s
Models a bank account using a mutable record + a user exception:
type account = { mutable balance : int }
exception Insufficient
let withdraw acct amt =
if amt > acct.balance then raise Insufficient
else acct.balance <- acct.balance - amt
Sequence:
start 100
deposit 50 150
withdraw 30 120
withdraw 200 raises Insufficient
handler returns acct.balance (= 120, transaction rolled back)
Combines mutable record fields, user exception declaration,
try-with-bare-pattern, and verifies that a raise in the middle of a
sequence doesn't leave a partial mutation.
59 baseline programs total.
This commit is contained in:
17
lib/ocaml/baseline/atm.ml
Normal file
17
lib/ocaml/baseline/atm.ml
Normal file
@@ -0,0 +1,17 @@
|
||||
type account = { mutable balance : int }
|
||||
|
||||
exception Insufficient
|
||||
|
||||
let withdraw acct amt =
|
||||
if amt > acct.balance then raise Insufficient
|
||||
else acct.balance <- acct.balance - amt
|
||||
|
||||
let deposit acct amt = acct.balance <- acct.balance + amt
|
||||
|
||||
;;
|
||||
|
||||
let a = { balance = 100 } in
|
||||
deposit a 50;
|
||||
withdraw a 30;
|
||||
try (withdraw a 200; -1)
|
||||
with Insufficient -> a.balance
|
||||
@@ -2,6 +2,7 @@
|
||||
"ackermann.ml": 125,
|
||||
"anagram_check.ml": 2,
|
||||
"anagrams.ml": 3,
|
||||
"atm.ml": 120,
|
||||
"bag.ml": 3,
|
||||
"bf_full.ml": 6,
|
||||
"bigint_add.ml": 28,
|
||||
|
||||
Reference in New Issue
Block a user