MathViz Examples

Learn MathViz by example. All examples on this page compile and run correctly with the MathViz compiler.

Run Examples

Save any example to a .mviz file and run with mathviz exec file.mviz

Basics

Hello World

MathViz
fn main() {
    println("Hello, MathViz!")
}

Variables

MathViz
fn main() {
    let x = 10
    let y = 20
    let sum = x + y
    println(f"Sum: {sum}")
}

Lists

MathViz
fn main() {
    let numbers = [1, 2, 3, 4, 5]
    for n in numbers {
        println(f"Number: {n}")
    }
}

Tuples

MathViz
fn main() {
    let point = (3.0, 4.0)
    let (x, y) = point
    println(f"x={x}, y={y}")
}

Functions

Basic Function

MathViz
fn add(a: Int, b: Int) -> Int {
    return a + b
}

fn main() {
    let result = add(5, 3)
    println(f"5 + 3 = {result}")
}

Lambda Expressions

MathViz
fn main() {
    let square = |x| x * x
    let result = square(5)
    println(f"5 squared = {result}")
}

Structs

Basic Struct

MathViz
struct Point {
    x: Float
    y: Float
}

impl Point {
    fn new(x: Float, y: Float) -> Point {
        return Point { x: x, y: y }
    }

    fn distance(self, other: Point) -> Float {
        let dx = self.x - other.x
        let dy = self.y - other.y
        return sqrt(dx * dx + dy * dy)
    }
}

fn main() {
    let p1 = Point.new(0.0, 0.0)
    let p2 = Point.new(3.0, 4.0)
    let d = p1.distance(p2)
    println(f"Distance: {d}")
}

Enums

Simple Enum

MathViz
enum Color {
    Red
    Green
    Blue
}

fn main() {
    let c = Color.Red
    println("Color selected")
}

Control Flow

If/Else

MathViz
fn main() {
    let x = 10
    if x > 5 {
        println("x is greater than 5")
    } else {
        println("x is 5 or less")
    }
}

For Loop

MathViz
fn main() {
    for i in 0..5 {
        println(f"i = {i}")
    }
}

While Loop

MathViz
fn main() {
    let i = 0
    while i < 5 {
        println(f"i = {i}")
        i = i + 1
    }
}

Match Expression

MathViz
fn main() {
    let value = 2
    let result = match value {
        1 -> "one"
        2 -> "two"
        3 -> "three"
        _ -> "other"
    }
    println(result)
}

Manim Animations

Hello World Animation

MathViz
scene HelloWorld {
    fn construct(self) {
        let text = Text("Hello, World!")
        play(Write(text))
        wait(1.0)
    }
}

Circle Animation

MathViz
scene CircleAnimation {
    fn construct(self) {
        let circle = Circle(radius: 2.0)
        circle.set_color(BLUE)

        let label = MathTex("A = \\pi r^2")
        label.next_to(circle, DOWN)

        play(Create(circle))
        play(Write(label))
        wait(2.0)
    }
}

Run animations with:

Shell
mathviz run animation.mviz --preview

Numba / Performance

JIT Compiled Function

MathViz
@njit
fn compute_sum(n: Int) -> Int {
    let total = 0
    for i in 0..n {
        total = total + i
    }
    return total
}

fn main() {
    let result = compute_sum(100)
    println(f"Sum: {result}")
}

Next Steps