Quick Start
Get up and running with Charl in 5 minutes
Hello World
Create a file called hello.ch:
print("Hello, World!")
Run it:
charl run hello.ch
Output:
Hello, World!
Variables and Types
// Basic types
let x = 42 // int
let y = 3.14 // float
let name = "Charl" // string
let active = true // bool
// Arrays
let numbers = [1, 2, 3, 4, 5]
// Print values
print("x = " + str(x))
print("y = " + str(y))
print("name = " + name)
Basic Math with Tensors
// Create tensors
let a = tensor([1.0, 2.0, 3.0])
let b = tensor([4.0, 5.0, 6.0])
// Element-wise operations
let sum = tensor_add(a, b)
let product = tensor_mul(a, b)
// Reduction operations
let total = tensor_sum(a)
let average = tensor_mean(a)
print("Sum: " + str(total))
print("Mean: " + str(average))
Simple Neural Network
// Initialize weights
let w = tensor_randn([2, 1])
let b = tensor_zeros([1])
// Input
let x = tensor([1.0, 0.5])
// Forward pass
let z = nn_linear(x, w, b)
let output = nn_sigmoid(z)
print("Output: " + str(tensor_sum(output)))
Control Flow
// If-else
let score = 85
if score >= 90 {
print("Grade: A")
} else if score >= 80 {
print("Grade: B")
} else {
print("Grade: C")
}
// While loop
let i = 0
while i < 5 {
print("Iteration: " + str(i))
i = i + 1
}
// Match expression
let status = match score {
100 => "Perfect"
90 => "Excellent"
_ => "Good"
}
print(status)
Functions
// Define a function
fn square(x: float) -> float {
return x * x
}
// Call the function
let result = square(5.0)
print("5 squared = " + str(result))
// Function with multiple parameters
fn greet(name: string, age: int) -> string {
return "Hello, " + name + "! You are " + str(age) + " years old."
}
print(greet("Alice", 25))
Training a Model
Complete example of gradient descent:
// Initialize parameter
let x = tensor([0.0])
let lr = 0.1
let epochs = 50
let epoch = 0
// Optimize f(x) = (x - 5)^2 to find x = 5
while epoch < epochs {
// Forward
let x_val = tensor_item(x)
let loss = (x_val - 5.0) * (x_val - 5.0)
// Gradient: d/dx[(x-5)^2] = 2(x-5)
let grad = 2.0 * (x_val - 5.0)
// Update: x = x - lr * grad
let update = x_val - lr * grad
let x = tensor([update], [1])
// Print progress every 10 epochs
let mod_check = epoch % 10
if mod_check == 0 {
print("Epoch " + str(epoch) + ": x = " + str(x_val) + ", loss = " + str(loss))
}
epoch = epoch + 1
}
print("Final x: " + str(tensor_sum(x)))