Code Examples
Learn Pyro by exploring real code examples across different domains.
Basics
Hello World
The classic first program in Pyro.
print("Hello, World!")
Variables & Types
Type inference, mutability, and collections.
name = "Pyro"
version = 1.0
mut count = 0
langs = ["Pyro", "Rust", "Go"]
for lang in langs
count = count + 1
print("{count}. {lang}")
Fibonacci
Recursive Fibonacci with pattern matching.
fn fib(n)
if n <= 1
return n
return fib(n - 1) + fib(n - 2)
for i in 0..20
print(fib(i))
Pipe Operator
Data transformations that read left to right.
words = "hello world from pyro"
parts = words |> split(" ") |> map(|w| capitalize(w))
result = parts |> join(" ")
print(result)
# "Hello World From Pyro"
nums = [1,2,3,4,5,6,7,8,9,10]
evens = nums |> filter(|x| x % 2 == 0) |> map(|x| x * x)
total = evens |> reduce(|a, b| a + b)
print(total)
# 220
Structs & Traits
Object-oriented design with traits.
struct Circle
radius = 0.0
struct Rect
w = 0.0
h = 0.0
fn circle_area(c)
return 3.14159 * c.radius * c.radius
fn rect_area(r)
return r.w * r.h
mut c = Circle()
c.radius = 5.0
print("Circle area: {circle_area(c)}")
mut r = Rect()
r.w = 4.0
r.h = 6.0
print("Rect area: {rect_area(r)}")
Web
HTTP Server
Build a REST API in 20 lines.
import web
fn home(req)
return web.html("<h1>Pyro API</h1>")
fn api_time(req)
import time
return web.json("{\"time\": {time.now()}}")
mut app = web.app()
app.get("/", home)
app.get("/api/time", api_time)
app.listen(3000)
WebSocket Chat
Real-time chat with WebSockets.
import websocket
import json
# Create a WebSocket server
wss = websocket.Server()
mut clients = []
fn on_connect(ws)
clients.push(ws)
ws.send("Welcome!")
fn on_message(ws, msg)
for c in clients
c.send(msg)
wss.on_connect(on_connect)
wss.on_message(on_message)
wss.listen(8080)
Data
CSV Analysis
Read CSV, compute statistics, find insights.
# Analyze data with Pyro
import math
data = [150, 230, 180, 310, 275, 190, 420]
total = data.sum()
count = data.len()
avg = total / count
print("Records: {count}")
print("Total: ${total}")
print("Average: ${avg}")
print("Max: ${data.max()}")
# Filter high values
high = data |> filter(|x| x > 200) |> sort
print("Above $200: {high}")
JSON Processing
Parse, transform, and serialize JSON.
import json
import fs
raw = fs.read("users.json")
users = json.parse(raw)
# Filter active users
active = users |> filter(|u| u["active"] == true)
output = json.stringify(active)
fs.write("active_users.json", output)
count = active.len()
print("Exported {count} users")
Security & Crypto
AES-256 Encryption
Encrypt and decrypt with AES-256-GCM.
import crypto
key = crypto.random_bytes(32)
secret = "Launch codes: 42-42-42"
# Encrypt
encrypted = crypto.encrypt(secret, key)
print("Encrypted: {encrypted}")
# Decrypt
decrypted = crypto.decrypt(encrypted, key)
print("Decrypted: {decrypted}")
assert(decrypted == secret)
Password Hashing
Secure password storage with PBKDF2.
import crypto
# Hash a password
hash = crypto.hash_sha256("s3cret")
print("Hash: {hash}")
# Verify by re-hashing
check = crypto.hash_sha256("s3cret")
print(hash == check) # true
check2 = crypto.hash_sha256("wrong")
print(hash == check2) # false
Algorithms
QuickSort
Classic quicksort implementation.
fn quicksort(arr)
if arr.len() <= 1
return arr
pivot = arr[0]
rest = arr[1..]
lo = rest |> filter(|x| x < pivot)
hi = rest |> filter(|x| x >= pivot)
return quicksort(lo) + [pivot] + quicksort(hi)
data = [38, 27, 43, 3, 9, 82, 10]
print(quicksort(data))
# [3, 9, 10, 27, 38, 43, 82]
Graph BFS
Breadth-first search with the graph module.
import graph
import collections
g = graph.Graph()
g.add_edge("A", "B")
g.add_edge("A", "C")
g.add_edge("B", "D")
g.add_edge("C", "D")
g.add_edge("D", "E")
path = graph.bfs(g, "A", "E")
result = path |> join(" -> ")
print("Shortest path: {result}")
# Shortest path: A -> B -> D -> E
System
File Operations
Read, write, and traverse the file system.
import fs
import path
# Write a file
fs.write("output.txt", "Hello from Pyro!")
# Read it back
content = fs.read("output.txt")
print(content)
# List all .ro files
files = fs.list(".") |> filter(|p| path.extension(p) == "ro")
files |> each(|p| print("Found: {p}"))
Concurrent Tasks
Run tasks in parallel with async/await.
import time
# Run tasks and measure time
fn work(id)
mut sum = 0
for i in 0..100000
sum = sum + i
return sum
start = time.now()
for id in 0..5
result = work(id)
print("Task {id}: {result}")
elapsed = time.now() - start
print("All done in {elapsed} ms")
Statistical Analysis
Compute statistics on datasets with Pyro.
import math
# Compute mean, variance, and correlation
x = [1.0, 2.0, 3.0, 4.0, 5.0]
y = [2.1, 3.9, 6.2, 7.8, 10.1]
x_avg = x.sum() / x.len()
y_avg = y.sum() / y.len()
print("X mean: {x_avg}")
print("Y mean: {y_avg}")
# Manual slope calculation
mut num = 0.0
mut den = 0.0
for i in 0..5
num = num + (x[i] - x_avg) * (y[i] - y_avg)
den = den + (x[i] - x_avg) * (x[i] - x_avg)
slope = num / den
print("Slope: {slope}")
Pyro Paste — Real App
A full pastebin with web server, SQLite database, and routing — all in Pyro.
import web
import db
import random
mut conn = db.connect("pastes.db")
conn.exec("CREATE TABLE IF NOT EXISTS pastes (id TEXT, content TEXT)")
fn home(req)
return web.html("<h1>Pyro Paste</h1>")
fn create_paste(req)
id = random.randint(10000000, 99999999)
conn.exec("INSERT INTO pastes VALUES ('{id}', 'hello')")
return web.json("{\"id\": \"{id}\"}")
fn view_paste(req)
rows = conn.query("SELECT * FROM pastes LIMIT 1")
if rows.len() > 0
return web.html("<pre>Found paste</pre>")
return web.html("<h1>Not Found</h1>")
mut app = web.app()
app.get("/", home)
app.post("/api/paste", create_paste)
app.get("/view", view_paste)
app.listen(3000)
JWT Authentication
Create and verify JSON Web Tokens.
import jwt
secret = "my-secret-key"
# Create a token
payload = {"sub": "user_123", "role": "admin"}
token = jwt.sign(payload, secret)
print("Token: {token}")
# Verify and decode
try
claims = jwt.verify(token, secret)
print("User: {claims}")
catch e
print("Invalid: {e}")