Examples

Learn SUB by reading real programs. Each example includes the source code and expected output. Run them with subi or compile with subc.

Hello World

The classic first program. Declare a variable, concatenate strings, and print.

let name = "World"
let greeting = "Hello, " + name + "!"

println(greeting)

Output:

Hello, World!

FizzBuzz

The classic programming exercise. Print numbers 1–100, but print "Fizz" for multiples of 3, "Buzz" for multiples of 5, and "FizzBuzz" for multiples of both.

for i in range(1, 101) {
    if i % 15 == 0 {
        println("FizzBuzz")
    } elif i % 3 == 0 {
        println("Fizz")
    } elif i % 5 == 0 {
        println("Buzz")
    } else {
        println(i)
    }
}

Output (first 15 lines):

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

Fibonacci

Compute the first 20 Fibonacci numbers using a loop.

fn fibonacci(n) {
    let a = 0
    let b = 1
    let result = []

    for i in range(0, n) {
        push(result, a)
        let temp = a + b
        a = b
        b = temp
    }

    return result
}

let fibs = fibonacci(20)
for num in fibs {
    println(num)
}

Output:

0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181

Classes

Define a Point class with fields, create instances with .new, and access members with dot notation.

class Point {
    let x = 0
    let y = 0
}

let p1 = Point.new
p1.x = 10
p1.y = 20

let p2 = Point.new
p2.x = 3
p2.y = 4

# Calculate distance between two points
fn distance(a, b) {
    let dx = a.x - b.x
    let dy = a.y - b.y
    return sqrt(dx * dx + dy * dy)
}

println("p1 = (" + str(p1.x) + ", " + str(p1.y) + ")")
println("p2 = (" + str(p2.x) + ", " + str(p2.y) + ")")
println("Distance: " + str(distance(p1, p2)))

Output:

p1 = (10, 20)
p2 = (3, 4)
Distance: 18.7883

Switch / Case

Pattern matching over values. Cases support multiple values and there is no fall-through.

fn describe_day(day) {
    switch day {
        case "Monday":
            return "Start of the work week"
        case "Tuesday", "Wednesday", "Thursday":
            return "Midweek"
        case "Friday":
            return "Almost weekend!"
        case "Saturday", "Sunday":
            return "Weekend! 🎉"
        default:
            return "Unknown day"
    }
}

let days = ["Monday", "Wednesday", "Friday", "Saturday"]

for day in days {
    println(day + ": " + describe_day(day))
}

Output:

Monday: Start of the work week
Wednesday: Midweek
Friday: Almost weekend!
Saturday: Weekend! 🎉

Standard Library Tour

A quick tour of the standard library modules: math, arrays, strings, and io.

import math
import arrays
import strings
import io

# ── Math ──
io.heading("Math")
println("PI = " + str(math.PI))
println("sqrt(144) = " + str(math.sqrt(144)))
println("factorial(10) = " + str(math.factorial(10)))
println("is_prime(97) = " + str(math.is_prime(97)))
println("fib(10) = " + str(math.fib(10)))

# ── Arrays ──
io.heading("Arrays")
let nums = [5, 2, 8, 1, 9, 3, 7]
println("Sum: " + str(arrays.sum_int(nums)))
println("Sorted: " + str(arrays.sorted_int(nums)))
println("Has 8? " + str(arrays.has_int(nums, 8)))
println("Unique: " + str(arrays.unique_int([1, 2, 2, 3, 3, 3])))

# ── Strings ──
io.heading("Strings")
let msg = "Hello, SUB Language!"
println("Upper: " + upper(msg))
println("Words: " + str(strings.words(msg)))
println("Reverse: " + strings.reverse(msg))
println("Slug: " + strings.slugify("Hello World Example"))
println("Palindrome? " + str(strings.is_palindrome("racecar")))

# ── IO ──
io.heading("IO Colors")
println(io.green("✓ Build succeeded"))
println(io.yellow("⚠ Deprecated feature used"))
println(io.red("✗ Compilation failed"))
println(io.cyan("ℹ Processing 42 files..."))

Output:

═══ Math ═══
PI = 3.14159
sqrt(144) = 12
factorial(10) = 3628800
is_prime(97) = true
fib(10) = 55

═══ Arrays ═══
Sum: 35
Sorted: [1, 2, 3, 5, 7, 8, 9]
Has 8? true
Unique: [1, 2, 3]

═══ Strings ═══
Upper: HELLO, SUB LANGUAGE!
Words: ["Hello," "SUB" "Language!"]
Reverse: !egaugnaL BUS ,olleH
Slug: hello-world-example
Palindrome? true

═══ IO Colors ═══
✓ Build succeeded
⚠ Deprecated feature used
✗ Compilation failed
ℹ Processing 42 files...

More Examples

Error Handling

Try/catch/finally for robust error management.

fn safe_divide(a, b) {
    if b == 0 {
        throw "Division by zero"
    }
    return a / b
}

try {
    println(safe_divide(10, 0))
} catch err {
    println("Caught: " + err)
} finally {
    println("Done")
}

User Input

Interactive programs with stdin.

let name = input("What is your name? ")
let age = int(input("How old are you? "))

println("Hello, " + name + "!")
println("Next year you'll be " + str(age + 1))

Networking

HTTP requests with built-in net functions.

let response = net_fetch("https://httpbin.org/get")
println(response)

Next Steps