;; 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) )