MALDA™ Reference Manual

The AI-First Programming Language - Version 1.0.11

33. Examples

Suggested order: start with 33.0 if you already program. If you are learning programming, continue with 33.1, 33.4, 33.6, 33.7, and 33.8 before the AI and full-stack examples later in this chapter. After the core path, branch into Testing and Quality, Data and Databases, and Browser Apps.

33.0 First Look

Characteristic constructs, no API key. Same program as Examples/Basics/first_look.malda and the Home Quick Start. -> Review binds the prompt to the schema. Without await, the call is a rendered template; validate("Review", …) is the same check await would run on the model JSON.

schema Review {
    summary: string;
    issues: string[];
}

prompt codeReview(code, language) -> Review {
    system: "You are an expert reviewer of {language}.",
    user: "Review this {language} code:\n\n{code}"
}

var rendered = codeReview("function add(a, b) { return a + b; }", "javascript");
io.print(rendered.user);

var checked = validate("Review", {
    "summary": "Looks fine",
    "issues": []
});
if (checked.ok) {
    io.print("schema ok: " + checked.data.summary);
} else {
    io.print("schema failed: " + checked.error);
}

33.1 Hello World

io.print("Hello, World!");

33.2 Simple Class Example

Walkthrough: 11. Classes & Objects.

class Person {
    public var name;
    public var age;
    
    function Person(name, age) {
        this.name = name;
        this.age = age;
    }
    
    public function introduce() {
        io.print($"Hi, I'm {this.name} and I'm {this.age} years old.");
    }
}

var person = new Person("Alice", 25);
person.introduce();

33.3 Inheritance Example

Walkthrough: 11. Classes & Objects §11.3.

class Animal {
    public var name;
    
    function Animal(name) {
        this.name = name;
    }
    
    public function speak() {
        io.print(this.name + " makes a sound");
    }
}

class Dog extends Animal {
    function Dog(name) {
        super(name);
    }
    
    public function speak() {
        io.print($"{this.name} barks: Woof!");
    }
}

var dog = new Dog("Buddy");
dog.speak();

33.4 Factorial Function

function factorial(n) {
    if (n <= 1) {
        return 1;
    }
    return n * factorial(n - 1);
}

var result = factorial(5);
io.print($"Factorial of 5: {result}");

33.5 Calculator Class

class Calculator {
    private var result;
    
    function Calculator() {
        this.result = 0;
    }
    
    public function add(value) {
        this.result = this.result + value;
        return this;
    }
    
    public function getResult() {
        return this.result;
    }
}

var calc = new Calculator();
calc.add(10).add(20);
io.print($"Result: {calc.getResult()}");

33.6 FizzBuzz

function fizzBuzz(n) {
    var i = 1;
    while (i <= n) {
        if (i % 15 == 0) {
            io.print("FizzBuzz");
        } else if (i % 3 == 0) {
            io.print("Fizz");
        } else if (i % 5 == 0) {
            io.print("Buzz");
        } else {
            io.print(i);
        }
        i = i + 1;
    }
}

fizzBuzz(20);

33.7 Array Manipulation

var numbers = [1, 2, 3, 4, 5];
var sum = 0;
var i = 0;

while (i < numbers.length) {
    sum = sum + numbers[i];
    i = i + 1;
}

io.print($"Sum: {sum}");

33.8 Input/Output Example

Console input plus conversion. File, path, and environment how-to: 12. Input/Output.

var name = io.input("What is your name? ");
var ageStr = io.input("What is your age? ");
var age = int(ageStr);

io.print($"Hello, {name}! You are {age} years old.");

if (age >= 18) {
    io.print("You are an adult.");
} else {
    io.print("You are a minor.");
}

33.9 Simple Agent Example

This is a good transition point after the language fundamentals. It shows how MALDA's first-class AI features build on the same syntax introduced in the earlier examples.

var client = new OpenRouterClient();
var agent = new Agent(
    "Assistant",
    "helper",
    "You are a helpful assistant.",
    client
);

var response = agent.think("What is 2+2?");
io.print(response.content);

33.10 Test Command Output Modes

# Human-readable (default)
malda test

# Structured CI payload
malda test --format ci

# Write deterministic regression artifacts for failing properties
malda test --write-regression

# Write regressions to a custom directory
malda test --write-regression --regression-dir ./artifacts/regressions

33.11 Scaffolding Starters

# Scaffold a secure web API starter
malda new webapi my-api

# Scaffold a fullstack starter
malda new fullstack my-app

# Scaffold a browser canvas game
malda new game my-game

# Scaffold a canvas game plus @GET/@POST scores
malda new game my-scores --fullstack

# Override generated project naming tokens
malda new webapi my-api --name SalesPortal

# Overwrite scaffold files in an existing directory
malda new fullstack . --force

# Skip tests scaffolding
malda new webapi api-lite --no-tests

Generated starters include default malda test conventions, reusable security helper patterns, baseline security/rate-limit config examples, environment profile files in config/environments/, and deploy/observability placeholder configs. The game template skips those HTTP configs; next step is malda play app.malda. malda new game --fullstack also skips HTTP configs and compiles with --mode fullstack instead of malda play.

33.12 JavaScript Backend (API mode)

Compile MALDA source to browser JavaScript and use the DOM helper API:

malda compile Examples/Web/js/hello_dom.malda --mode js -o Examples/Web/js/hello_dom.js
malda compile Examples/Web/js/counter.malda --target js -o Examples/Web/js/counter.js
var root = dom.query("#app");
if (root != null) {
    dom.clear(root);

    var button = dom.create("button");
    dom.setText(button, "Click");
    dom.append(root, button);

    function handleClick() {
        println("clicked");
    }

    dom.on(button, "click", handleClick);
}

The JavaScript backend also supports sum types and match patterns in API mode:

type Response = Ok(value) | Err(message);

var r = Ok(42);
var text = match r {
    case Ok(v): "value: " + v;
    case Err(msg): "error: " + msg;
};

println(text);

33.13 JavaScript Backend (template mode)

Template mode source files use the .malda.html extension and support interpolation plus statement blocks:

malda compile Examples/Web/js/hello_template.malda.html --mode js -o Examples/Web/js/hello_template.generated.js
<div class="hello-template">
  <p>Message: {{ "Hello" }}</p>
  {% var count = 2; %}
  <p>Count: {{ count }}</p>
</div>

Load malda-js-runtime.js before the compiled template script in your host page.

33.14 JavaScript Backend (game canvas API)

Build a first interactive browser game using game.* in JavaScript mode:

malda compile Examples/Games/game_bounce.malda --mode js -o Examples/Games/game_bounce.js
var x = 100;
var speed = 220;

function update(dtMs) {
    var step = (speed * dtMs) / 1000;
    if (game.isKeyDown("arrowleft")) {
        x = x - step;
    }
    if (game.isKeyDown("arrowright")) {
        x = x + step;
    }
}

function render() {
    game.clear();
    game.fillRect(x, 140, 40, 40, "#33cc66");
    game.drawText("Use arrows", 10, 24, "#ffffff", "14px monospace");
}

game.createCanvas(640, 360, "#app");
game.setBackground("#202830");
game.start(update, render);

Key points: create the canvas before drawing/starting, scale movement by dtMs, and load malda-js-runtime.js before the compiled script. See Examples/Games/game_runtime_smoke_test.html for a direct browser smoke test host page. For PNG atlas blit and a scrolling camera, compile Examples/Games/game_sprite_smoke.malda. For key edges, touches, and gamepad, compile Examples/Games/game_input_smoke.malda. For AABB and circle overlap, compile Examples/Games/game_collision_smoke.malda. For a short side-scroller that uses images, camera, AABB, key edges, sample SFX, and startFixed together, compile Examples/Games/malda_platform.malda. For a larger tile-cave sample (Boulder Dash-style gravity, diamonds, and fireflies), compile Examples/Games/maldadash.malda.

33.14.1 Game Audio (v1 quick sample)

var startedAudio = false;

function update(dtMs) {
    if (!startedAudio && (game.isKeyDown(" ") || game.isMouseDown(0))) {
        game.audioInit();
        game.audioSetMasterVolume(0.4);
        startedAudio = true;
    }

    if (game.isKeyDown("a")) {
        game.audioPlayTone(440, 80, "square", 0.2);
    }
}

game.createCanvas(640, 360, "#app");
game.setBackground("#202830");
game.start(update, null);

Audio v1 uses game.audio* APIs in JavaScript mode. The API surface is intentionally stable for existing MALDA game scripts.

33.14.2 Pixel buffer blit

Write a CPU frame with game.setPixel, then upload it in one putImageData via game.blitPixels(). Packed RGB/RGBA arrays are also accepted. Compile the ray-tracer sample with:

malda compile Examples/Games/ray_tracer.malda --mode js -o Examples/Games/ray_tracer.js
game.createCanvas(320, 180, "#app");
game.createPixelBuffer();

function renderScanline(y) {
    var x = 0;
    while (x < 320) {
        game.setPixel(x, y, x % 256, y % 256, 80);
        x = x + 1;
    }
}

function update(dtMs) {
    renderScanline(0);
}

function render() {
    game.blitPixels();
}

game.start(update, render);

Colors are 0–255. Out-of-bounds setPixel writes are ignored. Prefer this path over per-pixel fillRect. See Examples/Games/ray_tracer.malda.

33.15 JavaScript Backend (three.js scene API)

Build a first 3D browser scene using three.* in JavaScript mode. The scene API, loop, loading order, and shader kernels are in 26.10 three.js Scene API:

malda compile Examples/Games/three_cube.malda --mode js -o Examples/Games/three_cube.js
var width = 800;
var height = 500;
var renderer = three.createRenderer(width, height, "#app");
three.setClearColor(renderer, "#101722");

var scene = three.createScene();
var camera = three.createPerspectiveCamera(70, width / height, 0.1, 100.0);
three.setPosition(camera, 0, 0, 5);

var geometry = three.createBoxGeometry(1, 1, 1);
var material = three.createStandardMaterial({ "color": "#44aaff" });
var cube = three.createMesh(geometry, material);
three.add(scene, cube);

var light = three.createDirectionalLight("#ffffff", 1.1);
three.setPosition(light, 2, 3, 4);
three.add(scene, light);

function render() {
    three.render(renderer, scene, camera);
}

Key points: load Examples/Web/wwwroot/vendor/three.min.js before malda-js-runtime.js, then the compiled MALDA script, then call MaldaApp.main(). See Examples/Games/three_runtime_smoke_test.html for a direct host page. For a PNG material map, a glTF cube, and lookAt, compile Examples/Games/three_textured.malda.

33.15.1 Shader materials

Move per-pixel work onto the GPU with three.createShaderMaterial and three.setUniform. The contract (types, subset, glsl.compile keys, IDE rename) is in 26.10.1 Shader kernels. Compile the realtime tracer with:

malda compile Examples/Games/three_shader_raytracer.malda --mode js -o Examples/Games/three_shader_raytracer.js
malda compile Examples/Games/three_shader_path_tunnel.malda --mode js -o Examples/Games/three_shader_path_tunnel.js
@shader()
function vertexMain() {
    vUv = uv;
    gl_Position = vec4(position.xy, 0.0, 1.0);
}

var vert = glsl.compile({
    varyings: ["vec2 vUv"],
    functions: ["vertexMain"],
    main: "vertexMain"
});

var material = three.createShaderMaterial({
    "vertexShader": vert,
    "fragmentShader": frag,
    "uniforms": { "uTime": 0 }
});
three.setUniform(material, "uTime", t);

Use three.createOrthographicCamera(-1, 1, 1, -1, 0, 1) and PlaneGeometry(2, 2) for a fullscreen pass. See Examples/Games/three_shader_raytracer.malda. A ShaderToy-style path-marching tunnel is Examples/Games/three_shader_path_tunnel.malda (Frostbyte, CC-BY-NC-SA-4.0).

33.16 Property Testing Quick Example

property intIdentity(x) {
    return (x + 0) == x;
}

malda test --iterations 80 --seed 1337

For full property-testing guidance (capability decorators, parity semantics, shrinking, and regression workflows), see Property Testing.

33.17 AI Pipeline (RAG)

End-to-end retrieval-augmented generation using the pipe operator (|>), VectorDB retriever, prompts, and typed JSON output. Examples:

dotnet run --project MaldaLang -- Examples/Prompts/rag_pipeline.malda
dotnet run --project MaldaLang -- Examples/Prompts/rag_function_pipeline.malda

Pipeline sketch:

schema Answer {
    text: string;
    sources: string[];
}

prompt answerPrompt(question, context) -> Answer {
    system: "Answer using only the provided context.";
    user: "Context:\n{context}\n\nQuestion: {question}"
}

function embedText(text) {
    return embedBagOfWords(text, 16);
}

var vdb = new VectorDB(16, "single");
vdb.init(embedText);
indexInto(vdb, docs);
var retriever = vdb.asRetriever({ topK: 2 });

var context = question |> retriever.get |> formatRetrievedDocs;
var parsed = mockResponse |> parseJson("Answer");

// With an LLM client (inline pipe or named function):
// await (question |> retriever.get |> formatRetrievedDocs
//     |> (ctx) => answerPrompt(question, ctx) |> runPrompt(client) |> parseJson("Answer"));

function ragAnswer(question, client) -> Answer {
    return question |> retriever.get |> formatRetrievedDocs
        |> (ctx) => answerPrompt(question, ctx) |> runPrompt(client) |> parseJson("Answer");
}
// var result = await ragAnswer(question, client);

See also: 7. Expressions (pipe operator), 13. Built-in Functions (AI pipeline helpers), 15. VectorDB (asRetriever), and 10. Prompts (schema declarations).

33.18 Server-driven UI (ui.*)

Language API: 24. Web UI Server Components (start at 23. Web UI Overview). Offline samples under Examples/Web/:

dotnet run --project MaldaLang -- Examples/Web/ui_event_loop.malda
dotnet run --project MaldaLang -- Examples/Web/ui_counter_dashboard.malda

See Also