-
Notifications
You must be signed in to change notification settings - Fork 0
Examples
Nishal K edited this page Sep 29, 2025
·
1 revision
This page contains practical examples demonstrating Veyra's features and capabilities. Each example includes the code and explanation of what it does.
- Basic Examples
- Control Flow
- Functions
- Classes and Objects
- Error Handling
- File Operations
- Web Development
- AI/ML Examples
- Advanced Examples
println("Hello, World!");
The classic first program that prints a greeting to the console.
// Numbers
let age = 25;
let pi = 3.14159;
// Strings
let name = "Alice";
let greeting = "Hello, " + name + "!";
// Booleans
let is_active = true;
let is_admin = false;
// Arrays
let numbers = [1, 2, 3, 4, 5];
let names = ["Alice", "Bob", "Charlie"];
// Dictionaries
let person = {
"name": "Alice",
"age": 30,
"city": "New York"
};
let a = 10;
let b = 3;
println("Addition: " + to_string(a + b)); // 13
println("Subtraction: " + to_string(a - b)); // 7
println("Multiplication: " + to_string(a * b)); // 30
println("Division: " + to_string(a / b)); // 3.333...
println("Modulus: " + to_string(a % b)); // 1
println("Power: " + to_string(pow(a, b))); // 1000
let age = 18;
if age >= 18 {
println("You are an adult");
} else {
println("You are a minor");
}
// Nested conditions
let score = 85;
if score >= 90 {
println("Grade: A");
} else if score >= 80 {
println("Grade: B");
} else if score >= 70 {
println("Grade: C");
} else {
println("Grade: F");
}
// For loop with range
for i in 0..5 {
println("Count: " + to_string(i));
}
// For loop with array
let fruits = ["apple", "banana", "orange"];
for fruit in fruits {
println("I like " + fruit);
}
// While loop
let counter = 0;
while counter < 5 {
println("Counter: " + to_string(counter));
counter = counter + 1;
}
fn greet(name) {
return "Hello, " + name + "!";
}
let message = greet("Alice");
println(message); // "Hello, Alice!"
fn calculate_area(width, height) {
return width * height;
}
let area = calculate_area(10, 5);
println("Area: " + to_string(area)); // "Area: 50"
fn factorial(n) {
if n <= 1 {
return 1;
} else {
return n * factorial(n - 1);
}
}
println("5! = " + to_string(factorial(5))); // "5! = 120"
class Person {
fn init(name, age) {
this.name = name;
this.age = age;
}
fn greet() {
return "Hello, I'm " + this.name + " and I'm " + to_string(this.age) + " years old.";
}
fn birthday() {
this.age = this.age + 1;
}
}
let alice = Person("Alice", 30);
println(alice.greet()); // "Hello, I'm Alice and I'm 30 years old."
alice.birthday();
println(alice.greet()); // "Hello, I'm Alice and I'm 31 years old."
class Animal {
fn init(name) {
this.name = name;
}
fn speak() {
return "Some sound";
}
}
class Dog extends Animal {
fn speak() {
return this.name + " says: Woof!";
}
fn fetch(item) {
return this.name + " fetches the " + item;
}
}
let dog = Dog("Buddy");
println(dog.speak()); // "Buddy says: Woof!"
println(dog.fetch("ball")); // "Buddy fetches the ball"
fn divide(a, b) {
try {
if b == 0 {
throw "Division by zero";
}
return a / b;
} catch error {
println("Error: " + error);
return 0;
}
}
println("Result: " + to_string(divide(10, 2))); // "Result: 5"
println("Result: " + to_string(divide(10, 0))); // "Error: Division by zero" then "Result: 0"
fn read_file_safe(filename) {
try {
let content = read_file(filename);
if content.startswith("Error") {
throw "Failed to read file: " + content;
}
return content;
} catch error {
println("File operation failed: " + error);
return "";
}
}
let content = read_file_safe("data.txt");
if len(content) > 0 {
println("File content: " + content);
}
// Writing to a file
let data = "Hello, World!\nThis is a test file.";
let result = write_file("test.txt", data);
println("Write result: " + result);
// Reading from a file
let content = read_file("test.txt");
println("File content: " + content);
// Listing directory contents
let files = list_dir(".");
println("Files in current directory:");
for file in files {
println("- " + file);
}
// Create sample data
let csv_data = "Name,Age,City\nAlice,30,New York\nBob,25,Los Angeles\nCharlie,35,Chicago";
write_file("people.csv", csv_data);
// Read and process the data
let file_content = read_file("people.csv");
let lines = split(file_content, "\n");
println("People data:");
for i in 1..len(lines) {
let fields = split(lines[i], ",");
if len(fields) >= 3 {
println(fields[0] + " is " + fields[1] + " years old and lives in " + fields[2]);
}
}
// Create a simple HTML page
let page_content = create_page(
"My First Web Page",
html_element("div", [
html_element("h1", "Welcome to Veyra!"),
html_element("p", "This is a simple web page created with Veyra."),
html_element("ul", [
html_element("li", "Easy to learn"),
html_element("li", "Powerful features"),
html_element("li", "Built-in web server")
])
]),
"body { font-family: Arial, sans-serif; margin: 40px; background: #f5f5f5; }"
);
// Start web server
web_serve(page_content, 8080);
println("Server started at http://localhost:8080");
// Create an interactive calculator
let calculator_html = create_page(
"Calculator",
html_element("div", {"id": "calculator"}, [
html_element("input", "", {"type": "text", "id": "display", "readonly": "true"}),
html_element("br"),
html_element("button", "7", {"onclick": "appendNumber('7')"}),
html_element("button", "8", {"onclick": "appendNumber('8')"}),
html_element("button", "9", {"onclick": "appendNumber('9')"}),
html_element("button", "+", {"onclick": "setOperation('+')"}),
html_element("br"),
html_element("button", "4", {"onclick": "appendNumber('4')"}),
html_element("button", "5", {"onclick": "appendNumber('5')"}),
html_element("button", "6", {"onclick": "appendNumber('6')"}),
html_element("button", "-", {"onclick": "setOperation('-')"}),
html_element("br"),
html_element("button", "1", {"onclick": "appendNumber('1')"}),
html_element("button", "2", {"onclick": "appendNumber('2')"}),
html_element("button", "3", {"onclick": "appendNumber('3')"}),
html_element("button", "*", {"onclick": "setOperation('*')"}),
html_element("br"),
html_element("button", "0", {"onclick": "appendNumber('0')"}),
html_element("button", "C", {"onclick": "clearDisplay()"}),
html_element("button", "=", {"onclick": "calculate()"}),
html_element("button", "/", {"onclick": "setOperation('/')"})
]),
"
#calculator { width: 200px; margin: 50px auto; }
button { width: 40px; height: 40px; margin: 2px; font-size: 18px; }
#display { width: 190px; height: 30px; margin-bottom: 10px; font-size: 20px; text-align: right; }
"
);
// Add JavaScript for calculator functionality
let js_code = "
let display = '';
let operation = null;
let previousValue = null;
function appendNumber(num) {
display += num;
document.getElementById('display').value = display;
}
function setOperation(op) {
if (display !== '') {
previousValue = parseFloat(display);
operation = op;
display = '';
}
}
function calculate() {
if (previousValue !== null && display !== '' && operation) {
const currentValue = parseFloat(display);
let result;
switch(operation) {
case '+': result = previousValue + currentValue; break;
case '-': result = previousValue - currentValue; break;
case '*': result = previousValue * currentValue; break;
case '/': result = previousValue / currentValue; break;
}
display = result.toString();
document.getElementById('display').value = display;
operation = null;
previousValue = null;
}
}
function clearDisplay() {
display = '';
operation = null;
previousValue = null;
document.getElementById('display').value = '';
}
";
let full_page = calculator_html + "<script>" + js_code + "</script>";
// Start the web server
web_serve(full_page, 8081);
println("Calculator app running at http://localhost:8081");
// Create matrices
let matrix_a = [
[1, 2, 3],
[4, 5, 6]
];
let matrix_b = [
[7, 8],
[9, 10],
[11, 12]
];
// Matrix multiplication
let result = matrix_multiply(matrix_a, matrix_b);
println("Matrix multiplication result:");
for row in result {
println(to_string(row));
}
// Simulate a simple neural network layer
let inputs = [0.5, 0.3, 0.8];
let weights = [0.2, 0.4, 0.6];
let bias = 0.1;
// Calculate weighted sum
let weighted_sum = bias;
for i in 0..len(inputs) {
weighted_sum = weighted_sum + inputs[i] * weights[i];
}
// Apply activation function
let output = relu(weighted_sum);
println("Neural network output: " + to_string(output));
// Sample data: house sizes vs prices
let sizes = [1000, 1200, 1500, 1800, 2000];
let prices = [200000, 240000, 300000, 360000, 400000];
// Train linear regression model
let model = ai_linear_regression(sizes, prices);
println("Linear regression model:");
println("Slope: " + to_string(model["slope"]));
println("Intercept: " + to_string(model["intercept"]));
// Make a prediction
let new_size = 1600;
let predicted_price = model["slope"] * new_size + model["intercept"];
println("Predicted price for 1600 sq ft house: $" + to_string(predicted_price));
// Create a channel for communication
let chan = channel();
// Producer function (runs in background)
fn producer() {
for i in 1..6 {
send(chan, "Message " + to_string(i));
sleep(0.5); // Simulate work
}
send(chan, "DONE");
}
// Consumer function
fn consumer() {
while true {
let message = receive(chan);
if message == "DONE" {
break;
}
println("Received: " + message);
}
}
// Start producer in background
producer(); // This would run in background in a real implementation
// Run consumer
consumer();
println("Concurrent example completed");
// Read data from file, process it, and write results
fn process_data() {
try {
// Read input data
let input_data = read_file("input.txt");
if input_data.startswith("Error") {
throw "Failed to read input file";
}
// Process the data (convert to uppercase and count words)
let processed = upper(input_data);
let words = split(processed, " ");
let word_count = len(words);
// Create output
let output = "Processed text:\n" + processed + "\n\nWord count: " + to_string(word_count);
// Write results
let write_result = write_file("output.txt", output);
if write_result.startswith("Error") {
throw "Failed to write output file";
}
println("Data processing completed successfully");
println("Word count: " + to_string(word_count));
} catch error {
println("Error in data processing: " + error);
}
}
process_data();
// Simple REST API server
fn create_api_response(data) {
return json_stringify({
"status": "success",
"data": data,
"timestamp": time_now()
});
}
fn handle_get_users() {
let users = [
{"id": 1, "name": "Alice", "email": "[email protected]"},
{"id": 2, "name": "Bob", "email": "[email protected]"},
{"id": 3, "name": "Charlie", "email": "[email protected]"}
];
return create_api_response(users);
}
fn handle_get_user(id) {
let users = [
{"id": 1, "name": "Alice", "email": "[email protected]"},
{"id": 2, "name": "Bob", "email": "[email protected]"},
{"id": 3, "name": "Charlie", "email": "[email protected]"}
];
for user in users {
if user["id"] == id {
return create_api_response(user);
}
}
return json_stringify({
"status": "error",
"message": "User not found",
"timestamp": time_now()
});
}
// Create API documentation page
let api_page = create_page(
"Veyra API",
html_element("div", [
html_element("h1", "Veyra REST API"),
html_element("h2", "Endpoints"),
html_element("ul", [
html_element("li", html_element("code", "GET /api/users") + " - Get all users"),
html_element("li", html_element("code", "GET /api/users/{id}") + " - Get user by ID")
]),
html_element("h2", "Example Responses"),
html_element("pre", json_stringify({
"status": "success",
"data": [{"id": 1, "name": "Alice"}],
"timestamp": 1234567890
}, null, 2))
]),
"body { font-family: monospace; margin: 40px; } code { background: #f4f4f4; padding: 2px 4px; }"
);
// Start the API server
web_serve(api_page, 3000);
println("API server running at http://localhost:3000");
These examples demonstrate the breadth of Veyra's capabilities, from basic programming constructs to advanced features like web development, AI/ML, and concurrent programming. For the complete list of built-in functions, see the Standard Library page. For language syntax details, see the Language Guide.