Bank Account
A bank account that can be opened, closed, paid into and drawn from, by many tasks at once, without its balance going wrong.
Adapted from Exercism’s problem specification (MIT). Listed under Games & Simulation.
// FILE: bank_account.nomi
//# A bank account that many tasks may use at once. Its balance belongs to
//# one task, the teller, which handles one request at a time; an `Account`
//# is the address of that task, and each operation is a request and the
//# teller's answer.
import
std::channels.{Channel, Receiver, Sender}
std::tasks.Task
end
/// Why an operation is refused.
pub enum Error
AccountNotOpen
AccountAlreadyOpen
AmountNotPositive
AmountAboveBalance
end
impl Display for Error
fn to_string(error: Error) -> String
case error
.AccountNotOpen -> "account not open"
.AccountAlreadyOpen -> "account already open"
.AmountNotPositive -> "amount must be greater than 0"
.AmountAboveBalance -> "amount must be less than balance"
end
end
end
/// What a caller asks the teller, with the channel to answer on.
enum Request
Open {reply: Channel<Result<Unit, Error>>}
Close {reply: Channel<Result<Unit, Error>>}
Deposit {amount: Int, reply: Channel<Result<Unit, Error>>}
Withdraw {amount: Int, reply: Channel<Result<Unit, Error>>}
Balance {reply: Channel<Result<Int, Error>>}
end
/// An account: the address of its teller. Copies of it reach the same
/// balance.
pub opaque type Account Sender<Request>
impl Account
/// Opens the account with a balance of 0.
pub fn open(account: Account) -> Result<Unit, Error>
ask(account, fn reply -> .Open{reply:})
end
/// Closes the account. A closed account can be opened again, empty.
pub fn close(account: Account) -> Result<Unit, Error>
ask(account, fn reply -> .Close{reply:})
end
/// Adds `amount` to the balance.
pub fn deposit(account: Account, amount: Int) -> Result<Unit, Error>
ask(account, fn reply -> .Deposit{amount:, reply:})
end
/// Takes `amount` from the balance, which must hold it.
pub fn withdraw(account: Account, amount: Int) -> Result<Unit, Error>
ask(account, fn reply -> .Withdraw{amount:, reply:})
end
/// The balance of an open account.
pub fn balance(account: Account) -> Result<Int, Error>
ask(account, fn reply -> .Balance{reply:})
end
end
/// Runs `body` with a new account, not yet open, whose teller runs as a
/// task beside it, and returns what `body` returns. The teller stops when
/// `body` returns.
pub fn with_account<T>(body: (Account) -> T) -> T
inbox = Channel.buffered<Request>(16)
concurrent
teller = Task.spawn(fn -> serve(inbox.receiver))
result = body(Account(inbox.sender))
Sender.close(inbox.sender)
Task.await(teller)
result
end
end
/// Sends the request `request` builds around a fresh reply channel, and
/// waits for the answer.
fn ask<T>(account: Account, request: (Channel<T>) -> Request) -> T
Account(teller) = account
reply = Channel.buffered<T>(1)
Ok(_) = Sender.send(teller, request(reply)) else
unreachable "the teller listens until the account's body returns"
end
Some(answer) = Receiver.receive(reply.receiver) else
unreachable "the teller answers every request"
end
answer
end
/// The teller: answers requests one at a time until the inbox closes. The
/// balance is the loop's state, `None` while the account is not open.
fn serve(inbox: Receiver<Request>)
_ = Iter.loop(None, fn balance ->
case Receiver.receive(inbox)
Some(request) -> handle(balance, request)
None -> break balance
end
end)
end
/// Answers `request` against `balance` and returns the balance after it.
fn handle(balance: Maybe<Int>, request: Request) -> Maybe<Int>
case request
.Open{reply:} ->
answer(reply, balance, opened(balance))
.Close{reply:} ->
answer(reply, balance, closed(balance))
.Deposit{amount:, reply:} ->
answer(reply, balance, deposited(balance, amount))
.Withdraw{amount:, reply:} ->
answer(reply, balance, withdrawn(balance, amount))
.Balance{reply:} ->
_ = Sender.send(reply.sender, Maybe.to_result(balance, .AccountNotOpen))
balance
end
end
/// Sends `reply` whether `next` succeeded, and returns the balance after
/// it: the new one, or `balance` unchanged.
fn answer(
reply: Channel<Result<Unit, Error>>,
balance: Maybe<Int>,
next: Result<Maybe<Int>, Error>,
) -> Maybe<Int>
_ = Sender.send(reply.sender, Result.map(next, fn _ -> Unit))
Result.with_default(next, balance)
end
fn opened(balance: Maybe<Int>) -> Result<Maybe<Int>, Error>
case balance
Some(_) -> Err(.AccountAlreadyOpen)
None -> Ok(Some(0))
end
end
fn closed(balance: Maybe<Int>) -> Result<Maybe<Int>, Error>
case balance
Some(_) -> Ok(None)
None -> Err(.AccountNotOpen)
end
end
fn deposited(balance: Maybe<Int>, amount: Int) -> Result<Maybe<Int>, Error>
Some(current) = balance else return Err(.AccountNotOpen)
if amount <= 0 then return Err(.AmountNotPositive)
Ok(Some(current + amount))
end
fn withdrawn(balance: Maybe<Int>, amount: Int) -> Result<Maybe<Int>, Error>
Some(current) = balance else return Err(.AccountNotOpen)
if amount <= 0 then return Err(.AmountNotPositive)
if amount > current then return Err(.AmountAboveBalance)
Ok(Some(current - amount))
end
// FILE: bank_account_test.nomi
import
std::tasks.Task
bank_account
bank_account.{Account, Error}
end
/// One canonical operation before the last balance check.
enum Step
Open
Close
Deposit Int
Withdraw Int
end
/// Runs `steps` on a new account, stopping at the first refused one, and
/// returns the balance after them or the refusal.
fn replay(steps: List<Step>) -> Result<Int, Error>
bank_account.with_account(fn account ->
_ = steps |> Iter.map(&run(account, &1)) |> Result.collect()?
Account.balance(account)
end)
end
fn run(account: Account, step: Step) -> Result<Unit, Error>
case step
.Open -> Account.open(account)
.Close -> Account.close(account)
.Deposit(amount) -> Account.deposit(account, amount)
.Withdraw(amount) -> Account.withdraw(account, amount)
end
end
test "bank account"
[
("Newly opened account has zero balance", [Step.Open], Ok(0)),
("Single deposit", [.Open, .Deposit(100)], Ok(100)),
("Multiple deposits", [.Open, .Deposit(100), .Deposit(50)], Ok(150)),
("Withdraw once", [.Open, .Deposit(100), .Withdraw(75)], Ok(25)),
("Withdraw twice", [.Open, .Deposit(100), .Withdraw(80), .Withdraw(20)], Ok(0)),
(
"Can do multiple operations sequentially",
[.Open, .Deposit(100), .Deposit(110), .Withdraw(200), .Deposit(60), .Withdraw(50)],
Ok(20),
),
("Cannot check balance of closed account", [.Open, .Close], Err(Error.AccountNotOpen)),
(
"Cannot deposit into closed account",
[.Open, .Close, .Deposit(50)],
Err(.AccountNotOpen),
),
("Cannot deposit into unopened account", [.Deposit(50)], Err(.AccountNotOpen)),
(
"Cannot withdraw from closed account",
[.Open, .Close, .Withdraw(50)],
Err(.AccountNotOpen),
),
("Cannot close an account that was not opened", [.Close], Err(.AccountNotOpen)),
("Cannot open an already opened account", [.Open, .Open], Err(.AccountAlreadyOpen)),
("Reopened account does not retain balance", [.Open, .Deposit(50), .Close, .Open], Ok(0)),
(
"Cannot withdraw more than deposited",
[.Open, .Deposit(25), .Withdraw(50)],
Err(.AmountAboveBalance),
),
(
"Cannot withdraw negative",
[.Open, .Deposit(100), .Withdraw(-50)],
Err(.AmountNotPositive),
),
("Cannot deposit negative", [.Open, .Deposit(-50)], Err(.AmountNotPositive)),
]
|> subtests (description, steps, expected), description
assert replay(steps) == expected
end
end
test "Can handle concurrent transactions"
(opened, transactions, balance) = bank_account.with_account(fn account ->
opened = Account.open(account)
transactions = concurrent
1..=1000
|> Task.spawn_all(
fn _ ->
Account.deposit(account, 1)?
Account.withdraw(account, 1)
end,
max_running: 100,
)
|> Task.await_all()
end
(opened, transactions, Account.balance(account))
end)
assert opened == Ok(Unit)
assert transactions |> Iter.all_match(Result.is_ok)
assert balance == Ok(0)
end
test "errors read as the canonical messages"
assert "${Error.AccountNotOpen}" == "account not open"
assert "${Error.AccountAlreadyOpen}" == "account already open"
assert "${Error.AmountNotPositive}" == "amount must be greater than 0"
assert "${Error.AmountAboveBalance}" == "amount must be less than balance"
endok bank account (16 cases)
ok Can handle concurrent transactions
ok errors read as the canonical messages
test result: ok. 18 passed, 0 failed
How it’s written
Section titled “How it’s written”- Adapted: the exercise asks for a mutable account object whose methods change its balance, safely under concurrent calls. Nomi values are immutable, so the balance is the state of one task, the teller, which handles requests one at a time (
std::tasksandstd::channels). AnAccountis the teller’s inbox, and each operation sends a request with its own reply channel and waits for the answer. Two tasks never touch the balance, so there is nothing to lock. Accountis an opaque type over theSenderhalf of the teller’s inbox, and the operations are its functions (Account.deposit(account, 1)). Code outside the file cannot take it apart, soRequeststays private.with_account(body)makes an account that is not open yet, runs its teller besidebodyinside aconcurrentblock, closes the inbox whenbodyreturns, and returns whatbodyreturns. A teller cannot outlive the block that spawned it, so the account is scoped tobodyrather than returned.- The teller is an
Iter.loopwhose state is the balance,Nonewhile the account is not open.handlehandles one request with the pure functionsopened,closed,depositedandwithdrawn, which check in the canonical order: not open, then a non-positive amount, then an amount above the balance. - The four canonical errors are an
Errorenum with animpl Displaygiving the canonical messages, which one test checks. - The canonical cases are lists of operations ending in the one whose result is expected. The test file’s
replayruns a case’s operations asSteps on a new account, stopping at the first refused one, and then asks the balance, so each row is the operations before the final balance check and the expectedResult<Int, Error>. A case that ends in a refused operation never reaches the balance check. - The 16 sequential cases are one
subteststable named by the description column. “Can handle concurrent transactions” is its own test: 1000 tasks (100 running at once,Task.spawn_all) each deposit 1 and withdraw 1, and the balance is 0 after.