Docs Examples Why Mantra About Language Tour Download GitHub
14 Runnable Examples — including mantra.web, mantra.rest, mantra.sql.orm v0.2.0

Mantra by Example

Every snippet below is a real, runnable .mantra file. Examples 12–14 use v0.2.0 packages. Run with
mantrac <file.mantra> or compile to native with mantrac --emit native <file.mantra>

01. Hello World & Fundamentals

Variables (let/mut), functions with type annotations, conditionals, while loops.

def add(a: Int, b: Int) -> Int: return a + b def multiply(x: Float, y: Float) -> Float: return x * y def main() -> Int: # Immutable binding let message = "Hello, Developer! Mantra is up and running." print(message) let sum = add(42, 58) print("Sum of 42 + 58 = " + str(sum)) let product = multiply(3.14159, 2.0) print("Product = " + str(product)) if sum > 50: print("Sum is greater than 50!") # Mutable variable + while loop mut count = 3 while count > 0: print("Tick... " + str(count)) count = count - 1 print("Liftoff! Mantra is ready.") return 0
Terminal Output
Hello, Developer! Mantra is up and running. Sum of 42 + 58 = 100 Product = 6.28318 Sum is greater than 50! Tick... 3 Tick... 2 Tick... 1 Liftoff! Mantra is ready.

02. Classes & Encapsulation

Class declaration, __init__, self, pub def, private fields with underscore convention.

# Classes and Encapsulation class BankAccount: def __init__(self, owner: String, initial_balance: Float): self.owner = owner self._balance = initial_balance self.account_number = "ACT-1001" pub def deposit(self, amount: Float): if amount > 0.0: self._balance = self._balance + amount print("Deposited $" + str(amount)) pub def withdraw(self, amount: Float) -> Bool: if amount > self._balance: print("Insufficient funds!") return False self._balance = self._balance - amount return True pub def balance(self) -> Float: return self._balance pub def get_summary(self) -> String: return "Account[" + self.account_number + "] for " + self.owner def main() -> Int: account = BankAccount("Alice Smith", 500.0) print(account.get_summary()) account.deposit(250.0) let ok = account.withdraw(100.0) print("Final balance: $" + str(account.balance())) return 0
Terminal Output
Account[ACT-1001] for Alice Smith Deposited $250.0 Final balance: $650.0

03. Interfaces & Polymorphism

Define a Shape interface; Circle and Rectangle implement it. Polymorphic dispatch via interface type.

# Interfaces and Subtype Polymorphism interface Shape: def area(self) -> Float def name(self) -> String class Circle implements Shape: def __init__(self, radius: Float): self.radius = radius pub def area(self) -> Float: return 3.14159 * self.radius * self.radius pub def name(self) -> String: return "Circle" class Rectangle implements Shape: def __init__(self, width: Float, height: Float): self.width = width self.height = height pub def area(self) -> Float: return self.width * self.height pub def name(self) -> String: return "Rectangle" def print_shape(shape: Shape): print(shape.name() + " area: " + str(shape.area())) def main() -> Int: c = Circle(5.0) r = Rectangle(4.0, 6.0) print_shape(c) print_shape(r) return 0
Terminal Output
Circle area: 78.53975 Rectangle area: 24.0

04. Inheritance & Method Override

Extend a base class with extends, call super().__init__(), and override parent methods.

# Inheritance with super() and override class Animal: def __init__(self, name: String): self.name = name pub def speak(self) -> String: return "..." pub def get_name(self) -> String: return self.name class Dog extends Animal: def __init__(self, name: String): super().__init__(name) override pub def speak(self) -> String: return "Woof!" class Cat extends Animal: def __init__(self, name: String): super().__init__(name) override pub def speak(self) -> String: return "Meow!" def main() -> Int: dog = Dog("Rex") cat = Cat("Whiskers") print(dog.get_name() + " says: " + dog.speak()) print(cat.get_name() + " says: " + cat.speak()) return 0
Terminal Output
Rex says: Woof! Whiskers says: Meow!

05. Abstract Classes

Abstract class with abstract def forces subclasses to implement; shared default behaviour lives in the abstract class.

# Abstract Classes — enforce contracts on subclasses abstract class Repository: abstract def get_by_id(self, id: Int) -> String pub def exists(self, id: Int) -> Bool: return self.get_by_id(id) != "not_found" class InMemoryRepository extends Repository: def __init__(self): self.item = "Mantra Developer" override pub def get_by_id(self, id: Int) -> String: if id == 1: return self.item return "not_found" def main() -> Int: repo = InMemoryRepository() print("Found: " + repo.get_by_id(1)) print("Exists ID 1: " + str(repo.exists(1))) print("Exists ID 99: " + str(repo.exists(99))) return 0
Terminal Output
Found: Mantra Developer Exists ID 1: True Exists ID 99: False

06. Static Members

Class-level static constants and static def functions. Access without instantiation via ClassName.method().

# Static Members: class-level constants and functions class MathUtils: static PI: Float = 3.14159 static def square(value: Int) -> Int: return value * value static def cube(value: Int) -> Int: return value * value * value static def circle_area(radius: Float) -> Float: return MathUtils.PI * radius * radius def main() -> Int: print("Square(7) = " + str(MathUtils.square(7))) print("Cube(3) = " + str(MathUtils.cube(3))) print("Circle r=5: " + str(MathUtils.circle_area(5.0))) print("PI = " + str(MathUtils.PI)) return 0
Terminal Output
Square(7) = 49 Cube(3) = 27 Circle r=5: 78.53975 PI = 3.14159

07. Properties (@property)

Computed @property getters: convert Celsius to Fahrenheit and Kelvin without storing redundant fields.

# @property — computed attribute getters class Temperature: def __init__(self, c: Float): self._celsius = c @property def celsius(self) -> Float: return self._celsius @property def fahrenheit(self) -> Float: return (self._celsius * 1.8) + 32.0 @property def kelvin(self) -> Float: return self._celsius + 273.15 def main() -> Int: temp = Temperature(25.0) print("Celsius: " + str(temp.celsius)) print("Fahrenheit: " + str(temp.fahrenheit)) print("Kelvin: " + str(temp.kelvin)) return 0
Terminal Output
Celsius: 25.0 Fahrenheit: 77.0 Kelvin: 298.15

08. Composition

Build a Car that owns an Engine. Pass objects as constructor arguments — composition over deep inheritance.

# Composition — build complex objects from simpler ones class Engine: def __init__(self, horsepower: Int): self.horsepower = horsepower pub def start(self) -> String: return "V8 Engine started with " + str(self.horsepower) + " HP" class Car: def __init__(self, model: String, engine: Engine): self.model = model self.engine = engine pub def drive(self) -> String: return self.model + " is driving! " + self.engine.start() def main() -> Int: eng = Engine(450) car = Car("Mantra GT", eng) print(car.drive()) return 0
Terminal Output
Mantra GT is driving! V8 Engine started with 450 HP

09. Stack Data Structure

Container class with List as internal storage. push(), pop(), peek(), and is_empty() semantics.

# IntStack — container class with push/pop/peek class IntStack: def __init__(self): self.items = [] self.count = 0 pub def push(self, item: Int): self.items.append(item) self.count = self.count + 1 pub def pop(self) -> Int: if self.count == 0: return -1 self.count = self.count - 1 return self.items.pop() pub def peek(self) -> Int: if self.count == 0: return -1 return self.items[self.count - 1] pub def is_empty(self) -> Bool: return self.count == 0 def main() -> Int: s = IntStack() s.push(10) s.push(20) s.push(30) print("Peek: " + str(s.peek())) # 30 print("Pop: " + str(s.pop())) # 30 print("Size: " + str(s.count)) # 2 return 0
Terminal Output
Peek: 30 Pop: 30 Size: 2

10. Multi-level Inheritance & super() Chain

Component → UIElement → Button. Each level calls super().describe() to build the description string.

# Multi-level inheritance + super() chain class Component: def __init__(self, id: String): self.id = id self.enabled = True pub def describe(self) -> String: return "Component[" + self.id + "]" class UIElement extends Component: def __init__(self, id: String, x: Int, y: Int): super().__init__(id) self.x = x self.y = y override pub def describe(self) -> String: return super().describe() + " at (" + str(self.x) + ", " + str(self.y) + ")" class Button extends UIElement: def __init__(self, id: String, x: Int, y: Int, label: String): super().__init__(id, x, y) self.label = label self.clicks = 0 pub def click(self): self.clicks = self.clicks + 1 override pub def describe(self) -> String: return super().describe() + " label='" + self.label + "'" def main() -> Int: btn = Button("btn_submit", 100, 200, "Submit") btn.click() btn.click() print(btn.describe()) print("Clicks: " + str(btn.clicks)) return 0
Terminal Output
Component[btn_submit] at (100, 200) label='Submit' Clicks: 2

11. REST API Pattern

Interface-driven database adapter, HTTP response model, and a main() wiring them together — the foundation of mantra.sql.orm and mantra.net.http.

# REST API pattern — interfaces, ORM, HTTP response interface DatabaseAdapter: def connect(self) -> Bool def execute(self, sql: String) -> String def get_driver_name(self) -> String class MySQLAdapter implements DatabaseAdapter: def __init__(self, host: String, port: Int): self.host = host self.port = port override pub def connect(self) -> Bool: print("[MySQL] Connecting to " + self.host + ":" + str(self.port)) return True override pub def execute(self, sql: String) -> String: return "[MySQL OK] " + sql override pub def get_driver_name(self) -> String: return "MySQL 8.0" class HttpResponse: def __init__(self, code: Int, body: String): self.code = code self.body = body pub def to_string(self) -> String: return "HTTP " + str(self.code) + " | " + self.body def main() -> Int: db = MySQLAdapter("127.0.0.1", 3306) db.connect() let result = db.execute("SELECT * FROM users") let res = HttpResponse(200, result) print(res.to_string()) return 0
Terminal Output
[MySQL] Connecting to 127.0.0.1:3306 HTTP 200 | [MySQL OK] SELECT * FROM users