typestar

Libro de cuentas en Mojo

Un struct de cuenta que cuida su propio saldo y lleva un historial corrido.

struct Account(Movable):
    var owner: String
    var cents: Int
    var history: List[String]

    def __init__(out self, var owner: String, opening: Int):
        self.owner = owner^
        self.cents = opening
        self.history = List[String]()

    def deposit(mut self, amount: Int) raises:
        if amount <= 0:
            raise Error("deposit must be positive")
        self.cents += amount
        self.history.append("deposit " + String(amount))

    def withdraw(mut self, amount: Int) raises:
        if amount > self.cents:
            raise Error("insufficient funds")
        self.cents -= amount
        self.history.append("withdraw " + String(amount))

    def balance(self) -> String:
        return String(self.cents // 100) + "." + String(self.cents % 100)


def attempt(mut account: Account, action: String, amount: Int):
    try:
        if action == "deposit":
            account.deposit(amount)
        else:
            account.withdraw(amount)
        print("ok      ", action, amount)
    except e:
        print("rejected", action, amount, "--", String(e))


def main():
    var account = Account("Ada", 5000)
    attempt(account, "deposit", 1250)
    attempt(account, "withdraw", 800)
    attempt(account, "deposit", -40)
    attempt(account, "withdraw", 99999)
    attempt(account, "deposit", 375)

    print("")
    print("ledger for", account.owner)
    for entry in account.history:
        print("  ", entry)
    print("closing balance:", account.balance())

Cómo funciona

  1. Account es dueño de su nombre owner y de un List[String] de entradas.
  2. deposit y withdraw van marcados raises y rechazan montos inválidos con Error.
  3. attempt envuelve cada llamada en try, así un rechazo imprime en vez de cortar la corrida.
  4. El reporte de cierre repasa el historial y formatea el saldo en dólares.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
50
Caracteres a escribir
1256
Tokens
351
Ritmo de tres estrellas
75 tpm

Al ritmo de tres estrellas de 75 tokens por minuto, este intento toma unos 281 segundos.

Escribe este fragmento

Paso 1 de 2 en Bis; paso 21 de 22 en Structs y traits.

← Anterior Siguiente →