← Todos los ejemplos
Ejemplo 11
Language basics
the core of the language in one place — constants, records,
- Categoría
- Puro: corre en cualquier sitio
- Permisos
- Ninguno
- Qué hace
- none
- Cómo ejecutarlo
- t0 run examples/11_language_basics.tz
- Lenguaje
>=0.1.1, <0.2.0
Código
// Purpose: the core of the language in one place — constants, records, // enums, functions, loops, match, Option and Result with `?`. // Category: pure // Permissions: none // Side effects: none // Run: t0 run examples/11_language_basics.tz lang ">=0.1.1, <0.2.0"; const TAKER_FEE: Ratio = bps(5); struct Order { side: Direction, size: Quantity, limit: Option<Price>, } enum Direction { Buy, Sell, } fn sign(side: Direction) -> Int { return match side { Direction.Buy => 1, Direction.Sell => -1, }; } /// Net position after a list of orders, in units. fn net(orders: List<Order>) -> Quantity { let mut total = qty(0); for o in orders { if sign(o.side) > 0 { total = total + o.size; } else { total = total - o.size; } } return total; } fn fee_of(o: Order) -> Result<Money, Error> { if o.limit.is_none() { return Err(error("E-NO-LIMIT", "a market order has no price to charge a fee on yet")); } let limit = o.limit.expect("checked above"); return Ok(limit * o.size * TAKER_FEE); } fn total_fees(orders: List<Order>) -> Result<Money, Error> { let mut total = money(0, USDT); for o in orders { total = total + fee_of(o)?; } return Ok(total); } fn main() { let orders = [ Order { side: Direction.Buy, size: qty(0.5), limit: Some(price(64000, USDT)) }, Order { side: Direction.Sell, size: qty(0.2), limit: Some(price(64500, USDT)) }, ]; print("net " + to_string(net(orders))); print(total_fees(orders)); let mut with_market = orders; with_market.push(Order { side: Direction.Buy, size: qty(1), limit: None }); match total_fees(with_market) { Ok(fees) => print(fees), Err(e) => print("refused: " + e.code), } let mut countdown = 3; while countdown > 0 { countdown = countdown - 1; } print("countdown " + to_string(countdown)); } // expect-output: net 0.3 // expect-output: Ok(22.45000 USDT) // expect-output: refused: E-NO-LIMIT // expect-output: countdown 0