Files
RustAst/examples/object_records.myc
T
Brummel 16af3ae9fc Refactor Examples to use assert_eq
This commit updates all example files to use `assert_eq!` for verifying
output, replacing the previous `Output:` comments. This change makes the
examples more robust and self-testing.

The benchmark results in some examples have also been slightly adjusted,
reflecting minor performance variations after the refactoring.

Additionally, a runtime panic handling mechanism has been introduced in
the VM for function calls, which improves error reporting for unexpected
panics.
2026-03-26 15:07:48 +01:00

53 lines
1.4 KiB
Plaintext

;; Benchmark: 1.3us
;; Benchmark-Repeat: 1528
; ---------------------------------------------------------
; Object-Oriented Records Example
; ---------------------------------------------------------
; This showcase treats a record as an object by storing
; closures that capture private state.
(do
; A factory function (Constructor) for a BankAccount object
(def make-account (fn [initial-balance]
(do
; 'balance' is a captured parameter, acting as private state
(def balance initial-balance)
{
; Method: Get current balance
:balance (fn [] balance)
; Method: Deposit money
:deposit (fn [amount]
(assign balance (+ balance amount)))
; Method: Withdraw money with validation
:withdraw (fn [amount]
(if (>= balance amount)
(assign balance (- balance amount))
"Insufficient funds"))
}
)))
; 1. Create an instance
(def my-acc (make-account 100))
; 2. deposit 50 -> balance is now 150
(def b1 ((.deposit my-acc) 50))
; 3. withdraw 20 -> balance is now 130
(def b2 ((.withdraw my-acc) 20))
; 4. withdraw 1000 -> insufficient funds
(def error-msg ((.withdraw my-acc) 1000))
; 5. balance getter
(def final-balance ((.balance my-acc)))
(assert-eq 150 b1)
(assert-eq 130 b2)
(assert-eq "Insufficient funds" error-msg)
(assert-eq 130 final-balance)
)