Examples
Real, copy-paste-ready code for common tasks. Click an example to view the code.
Basics
/*
* hello.ez - Your first EZ program
*
* Run with: ez examples/hello.ez
*/
import @std
using std
do main() {
println("Hello, World!")
}
/*
* variables.ez - Variable declarations and types
*
* EZ has two variable keywords:
* - temp: mutable (can be changed)
* - const: immutable (cannot be changed)
*/
import @std
using std
do main() {
println("=== Variables in EZ ===")
println("")
// Mutable variables with 'temp'
temp age int = 25
temp name string = "Alice"
temp score float = 95.5
temp active bool = true
temp grade char = 'A'
println("Initial values:")
println(" age = ${age}")
println(" name = ${name}")
println(" score = ${score}")
println(" active = ${active}")
println(" grade = ${grade}")
// temp variables can be changed
age = 26
name = "Bob"
println("")
println("After modification:")
println(" age = ${age}")
println(" name = ${name}")
// Immutable constants with 'const'
const PI float = 3.14159
const MAX_USERS int = 100
const APP_NAME string = "MyApp"
println("")
println("Constants:")
println(" PI = ${PI}")
println(" MAX_USERS = ${MAX_USERS}")
println(" APP_NAME = ${APP_NAME}")
// Numeric separators for readability
temp billion int = 1_000_000_000
temp precise float = 3.141_592_653
println("")
println("Numeric separators:")
println(" billion = ${billion}")
println(" precise = ${precise}")
}
/*
* control_flow.ez - Conditionals and loops
*
* EZ uses:
* - if / or / otherwise (not else if / else)
* - for with range()
* - for_each for collections
* - as_long_as (like while)
*/
import @std
using std
do main() {
println("=== Control Flow in EZ ===")
println("")
// if / or / otherwise
println("-- Conditionals --")
temp score int = 85
if score >= 90 {
println("Grade: A")
} or score >= 80 {
println("Grade: B")
} or score >= 70 {
println("Grade: C")
} otherwise {
println("Grade: F")
}
// for loop with range
println("")
println("-- For loop with range --")
println("Counting 1 to 5:")
for i in range(1, 6) {
println(" ${i}")
}
// for_each loop
println("")
println("-- For_each loop --")
temp fruits [string] = {"apple", "banana", "cherry"}
println("Fruits:")
for_each fruit in fruits {
println(" - ${fruit}")
}
// for_each with string
println("")
println("Letters in 'EZ':")
for_each ch in "EZ" {
println(" ${ch}")
}
// as_long_as loop (while equivalent)
println("")
println("-- As_long_as loop --")
temp count int = 0
as_long_as count < 3 {
println(" count = ${count}")
count++
}
// break and continue
println("")
println("-- Break and Continue --")
println("Numbers 1-10, skip evens, stop at 7:")
for i in range(1, 11) {
if i == 7 {
break
}
if i % 2 == 0 {
continue
}
println(" ${i}")
}
}
/*
* functions.ez - Defining and calling functions
*
* Functions in EZ use the 'do' keyword.
* Return types are specified with '->'
*/
import @std
using std
do main() {
println("=== Functions in EZ ===")
println("")
// Calling a simple function
greet()
// Function with parameters
greet_person("Alice")
greet_person("Bob")
// Function with return value
temp sum int = add(5, 3)
println("add(5, 3) = ${sum}")
// Function with multiple parameters
temp result float = calculate(10.0, 5.0, 2.0)
println("calculate(10, 5, 2) = ${result}")
// Recursive function
temp fact int = factorial(5)
println("factorial(5) = ${fact}")
// Function returning a string
temp msg string = get_greeting("World")
println(msg)
}
// Simple function with no parameters or return
do greet() {
println("Hello!")
}
// Function with a parameter
do greet_person(name string) {
println("Hello, ${name}!")
}
// Function with return type
do add(a int, b int) -> int {
return a + b
}
// Multiple parameters with shared types
do calculate(x float, y float, z float) -> float {
return (x + y) * z
}
// Recursive function
do factorial(n int) -> int {
if n <= 1 {
return 1
}
return n * factorial(n - 1)
}
// Function returning a string
do get_greeting(name string) -> string {
return "Welcome, ${name}!"
}
/*
* mutable_params.ez - Mutable vs Read-Only Parameters
*
* By default, function parameters are read-only.
* Use & to allow a function to modify its parameter.
*/
import @std
using std
const Person struct {
name string
age int
}
do main() {
println("=== Mutable Parameters ===")
println("")
// Create a person
temp alice Person = Person{name: "Alice", age: 30}
println("Initial: ${alice.name} is ${alice.age}")
// Read-only: get_info just reads the data
temp info string = get_info(alice)
println("Info: ${info}")
// Mutable: birthday modifies the person
birthday(&alice)
println("After birthday: ${alice.name} is ${alice.age}")
// Another birthday
birthday(&alice)
println("After another birthday: ${alice.name} is ${alice.age}")
// Arrays work the same way
println("")
println("-- Arrays --")
temp scores [int] = {85, 90, 78}
println("Before: ${scores}")
// Mutable: add_bonus modifies the array
add_bonus(&scores, 5)
println("After +5 bonus: ${scores}")
// Read-only: calculate_average just reads
temp avg float = calculate_average(scores)
println("Average: ${avg}")
}
// Read-only parameter (no &)
// Can read p but cannot modify it
do get_info(p Person) -> string {
// p.age = 100 // ERROR: cannot modify read-only parameter
return "${p.name}, age ${p.age}"
}
// Mutable parameter (with &)
// Can modify p
do birthday(&p Person) {
p.age = p.age + 1
}
// Read-only array parameter
do calculate_average(nums [int]) -> float {
temp sum int = 0
for_each n in nums {
sum = sum + n
}
return float(sum) / float(len(nums))
}
// Mutable array parameter
do add_bonus(&scores [int], bonus int) {
for i in range(0, len(scores)) {
scores[i] = scores[i] + bonus
}
}
Data Structures
/*
* arrays.ez - Working with arrays
*
* Arrays hold multiple values of the same type.
* Syntax: [type] for the type, {values} for literals
*/
import @std
using std
do main() {
println("=== Arrays in EZ ===")
println("")
// Declaring arrays
println("-- Array basics --")
temp numbers [int] = {1, 2, 3, 4, 5}
temp names [string] = {"Alice", "Bob", "Charlie"}
temp flags [bool] = {true, false, true}
println("numbers: ${numbers}")
println("names: ${names}")
println("flags: ${flags}")
// Accessing elements (0-indexed)
println("")
println("-- Accessing elements --")
println("numbers[0] = ${numbers[0]}")
println("numbers[2] = ${numbers[2]}")
println("names[1] = ${names[1]}")
// Modifying elements
println("")
println("-- Modifying elements --")
numbers[0] = 100
println("After numbers[0] = 100: ${numbers}")
// Array length
println("")
println("-- Array length --")
println("Length of numbers: ${len(numbers)}")
println("Length of names: ${len(names)}")
// Iterating over arrays
println("")
println("-- Iterating with for_each --")
println("All names:")
for_each name in names {
println(" - ${name}")
}
// Iterating with index
println("")
println("-- Iterating with index --")
for i in range(0, len(numbers)) {
println(" numbers[${i}] = ${numbers[i]}")
}
// Empty array
println("")
println("-- Empty array --")
temp empty [int] = {}
println("Empty array length: ${len(empty)}")
}
/*
* maps.ez - Working with maps (key-value pairs)
*
* Maps store key-value pairs.
* Syntax: map[key_type:value_type]
*/
import @std, @maps
using std
do main() {
println("=== Maps in EZ ===")
println("")
// Declaring maps
println("-- Map basics --")
temp ages map[string:int] = {
"Alice": 30,
"Bob": 25,
"Charlie": 35
}
temp scores map[string:float] = {
"math": 95.5,
"science": 88.0,
"history": 92.3
}
println("ages: ${ages}")
println("scores: ${scores}")
// Accessing values
println("")
println("-- Accessing values --")
temp alice_key string = "Alice"
temp math_key string = "math"
println("Alice's age: ${ages[alice_key]}")
println("Math score: ${scores[math_key]}")
// Modifying values
println("")
println("-- Modifying values --")
ages[alice_key] = 31
println("After birthday: Alice is ${ages[alice_key]}")
// Adding new entries
println("")
println("-- Adding entries --")
temp diana_key string = "Diana"
ages[diana_key] = 28
println("Added Diana: ${ages}")
// Map length
println("")
println("-- Map length --")
println("Number of people: ${len(ages)}")
// Iterating over maps using keys
println("")
println("-- Iterating over maps --")
println("All ages:")
temp keys [string] = maps.keys(ages)
for_each key in keys {
println(" ${key} is ${ages[key]} years old")
}
// Integer keys
println("")
println("-- Integer keys --")
temp lookup map[int:string] = {
1: "one",
2: "two",
3: "three"
}
println("lookup[2] = ${lookup[2]}")
}
/*
* structs.ez - Custom data structures
*
* Structs group related data together.
* Use 'const Name struct' to define, then create instances.
*/
import @std
using std
// Define a simple struct
const Person struct {
name string
age int
active bool
}
// Struct with numeric fields
const Point struct {
x float
y float
}
// Struct with an array field
const Team struct {
name string
members [string]
}
do main() {
println("=== Structs in EZ ===")
println("")
// Creating struct instances
println("-- Creating structs --")
temp alice Person = Person{
name: "Alice",
age: 30,
active: true
}
temp bob Person = Person{
name: "Bob",
age: 25,
active: false
}
println("Created alice and bob")
// Accessing fields
println("")
println("-- Accessing fields --")
println("alice.name = ${alice.name}")
println("alice.age = ${alice.age}")
println("alice.active = ${alice.active}")
// Modifying fields
println("")
println("-- Modifying fields --")
alice.age = 31
println("After birthday: alice.age = ${alice.age}")
// Using Point struct
println("")
println("-- Point struct --")
temp origin Point = Point{x: 0.0, y: 0.0}
temp target Point = Point{x: 3.0, y: 4.0}
println("origin: (${origin.x}, ${origin.y})")
println("target: (${target.x}, ${target.y})")
// Struct with array
println("")
println("-- Struct with array --")
temp devTeam Team = Team{
name: "Developers",
members: {"Alice", "Bob", "Charlie"}
}
println("Team: ${devTeam.name}")
println("Members: ${devTeam.members}")
// Pass struct to function
println("")
println("-- Structs in functions --")
print_person(alice)
print_person(bob)
}
// Function that takes a struct parameter
do print_person(p Person) {
println("${p.name} is ${p.age} years old")
}
/*
* enums.ez - Enumerations
*
* Enums define a type with a fixed set of values.
* Values are accessed with EnumName.VALUE syntax.
*/
import @std
using std
// Simple enum
const Color enum {
RED
GREEN
BLUE
}
// Enum for days
const Day enum {
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY
}
// Enum for status
const Status enum {
PENDING
ACTIVE
COMPLETED
CANCELLED
}
do main() {
println("=== Enums in EZ ===")
println("")
// Using enum values
println("-- Using enums --")
temp myColor Color = Color.RED
temp today Day = Day.FRIDAY
temp taskStatus Status = Status.PENDING
println("myColor = ${myColor}")
println("today = ${today}")
println("taskStatus = ${taskStatus}")
// Comparing enum values
println("")
println("-- Comparing enums --")
if myColor == Color.RED {
println("The color is red!")
}
if today == Day.FRIDAY {
println("It's Friday!")
}
// Using enums in conditionals
println("")
println("-- Enums in conditionals --")
print_day_type(Day.MONDAY)
print_day_type(Day.SATURDAY)
print_day_type(Day.WEDNESDAY)
// Changing enum values
println("")
println("-- Updating enum values --")
taskStatus = Status.ACTIVE
println("Status changed to: ${taskStatus}")
taskStatus = Status.COMPLETED
println("Status changed to: ${taskStatus}")
}
// Function using enum parameter
do print_day_type(d Day) {
if d == Day.SATURDAY {
println("${d} is a weekend day")
} or d == Day.SUNDAY {
println("${d} is a weekend day")
} otherwise {
println("${d} is a weekday")
}
}
Algorithms
/*
* fizzbuzz.ez - The classic FizzBuzz problem
*
* Print numbers 1 to 100, but:
* - For multiples of 3, print "Fizz"
* - For multiples of 5, print "Buzz"
* - For multiples of both, print "FizzBuzz"
*/
import @std
using std
do main() {
println("=== FizzBuzz ===")
println("")
for i in range(1, 101) {
if i % 15 == 0 {
println("FizzBuzz")
} or i % 3 == 0 {
println("Fizz")
} or i % 5 == 0 {
println("Buzz")
} otherwise {
println("${i}")
}
}
}
/*
* fibonacci.ez - The Fibonacci sequence
*
* Each number is the sum of the two preceding ones.
* 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
*/
import @std
using std
do main() {
println("=== Fibonacci Sequence ===")
println("")
// Print first 20 Fibonacci numbers
println("First 20 Fibonacci numbers:")
for i in range(0, 20) {
println(" fib(${i}) = ${fibonacci(i)}")
}
// Sum of first 10
println("")
temp sum int = 0
for i in range(0, 10) {
sum = sum + fibonacci(i)
}
println("Sum of first 10: ${sum}")
}
// Recursive Fibonacci
do fibonacci(n int) -> int {
if n <= 0 {
return 0
}
if n == 1 {
return 1
}
return fibonacci(n - 1) + fibonacci(n - 2)
}
/*
* primes.ez - Finding prime numbers
*
* A prime number is only divisible by 1 and itself.
*/
import @std
using std
do main() {
println("=== Prime Numbers ===")
println("")
// Check specific numbers
println("Checking individual numbers:")
println(" is_prime(2) = ${is_prime(2)}")
println(" is_prime(17) = ${is_prime(17)}")
println(" is_prime(20) = ${is_prime(20)}")
println(" is_prime(97) = ${is_prime(97)}")
// Find primes up to 50
println("")
println("Prime numbers up to 50:")
temp count int = 0
for n in range(2, 51) {
if is_prime(n) {
println(" ${n}")
count = count + 1
}
}
println("")
println("Found ${count} primes")
}
// Check if a number is prime
do is_prime(n int) -> bool {
if n < 2 {
return false
}
if n == 2 {
return true
}
if n % 2 == 0 {
return false
}
temp i int = 3
as_long_as i * i <= n {
if n % i == 0 {
return false
}
i = i + 2
}
return true
}
/*
* calculator.ez - A simple calculator
*
* Demonstrates functions for basic math operations.
*/
import @std
using std
do main() {
println("=== Simple Calculator ===")
println("")
// Demo calculations
temp a float = 10.0
temp b float = 3.0
println("a = ${a}")
println("b = ${b}")
println("")
// Basic operations
println("-- Basic Operations --")
println("add(${a}, ${b}) = ${add(a, b)}")
println("subtract(${a}, ${b}) = ${subtract(a, b)}")
println("multiply(${a}, ${b}) = ${multiply(a, b)}")
println("divide(${a}, ${b}) = ${divide(a, b)}")
// More operations
println("")
println("-- More Operations --")
println("power(2, 8) = ${power(2, 8)}")
println("absolute(-42) = ${absolute(-42)}")
println("max(15, 23) = ${maximum(15, 23)}")
println("min(15, 23) = ${minimum(15, 23)}")
// Chained calculations
println("")
println("-- Chained Calculations --")
temp result float = add(multiply(2.0, 3.0), 4.0)
println("(2 * 3) + 4 = ${result}")
result = divide(subtract(20.0, 8.0), 3.0)
println("(20 - 8) / 3 = ${result}")
}
// Basic arithmetic functions
do add(x float, y float) -> float {
return x + y
}
do subtract(x float, y float) -> float {
return x - y
}
do multiply(x float, y float) -> float {
return x * y
}
do divide(x float, y float) -> float {
if y == 0.0 {
println("Error: Division by zero!")
return 0.0
}
return x / y
}
// Power function (integer exponent)
do power(base int, exp int) -> int {
if exp == 0 {
return 1
}
temp result int = 1
for i in range(0, exp) {
result = result * base
}
return result
}
// Absolute value
do absolute(n int) -> int {
if n < 0 {
return -n
}
return n
}
// Maximum of two numbers
do maximum(a int, b int) -> int {
if a > b {
return a
}
return b
}
// Minimum of two numbers
do minimum(a int, b int) -> int {
if a < b {
return a
}
return b
}
Standard Library
/*
* using_stdlib.ez - Using the Standard Library
*
* EZ comes with built-in libraries:
* @std - Core functions (println, print, len)
* @math - Math operations
* @strings - String manipulation
* @arrays - Array utilities
* @maps - Map utilities
* @time - Time functions
*/
import @std, @math, @strings, @arrays, @maps, @time
using std
do main() {
println("=== Using the Standard Library ===")
println("")
// ==================
// @math library
// ==================
println("-- @math --")
println("math.abs(-42) = ${math.abs(-42)}")
println("math.sqrt(16) = ${math.sqrt(16.0)}")
println("math.pow(2, 10) = ${math.pow(2.0, 10.0)}")
println("math.min(5, 3) = ${math.min(5, 3)}")
println("math.max(5, 3) = ${math.max(5, 3)}")
println("math.floor(3.7) = ${math.floor(3.7)}")
println("math.ceil(3.2) = ${math.ceil(3.2)}")
println("math.round(3.5) = ${math.round(3.5)}")
println("math.random(100) = ${math.random(100)}")
println("")
// ==================
// @strings library
// ==================
println("-- @strings --")
temp text string = " Hello, World! "
println("Original: '${text}'")
println("strings.trim() = '${strings.trim(text)}'")
println("strings.upper() = '${strings.upper(text)}'")
println("strings.lower() = '${strings.lower(text)}'")
println("strings.len() = ${strings.len(text)}")
println("")
temp csv string = "apple,banana,cherry"
temp parts [string] = strings.split(csv, ",")
println("strings.split(csv, ',') = ${parts}")
temp separator string = " | "
temp joined string = strings.join(parts, separator)
println("strings.join(parts, ' | ') = '${joined}'")
println("")
temp hello string = "hello"
temp world string = "world"
temp ell string = "ell"
temp he string = "he"
temp lo string = "lo"
temp lowercase_l string = "l"
temp uppercase_L string = "L"
temp hello_world string = "hello world"
temp contains_result bool = strings.contains(hello_world, world)
println("strings.contains('hello world', 'world') = ${contains_result}")
temp starts_result bool = strings.starts_with(hello, he)
println("strings.starts_with('hello', 'he') = ${starts_result}")
temp ends_result bool = strings.ends_with(hello, lo)
println("strings.ends_with('hello', 'lo') = ${ends_result}")
temp replace_result string = strings.replace(hello, lowercase_l, uppercase_L)
println("strings.replace('hello', 'l', 'L') = '${replace_result}'")
temp index_result int = strings.index(hello, lowercase_l)
println("strings.index('hello', 'l') = ${index_result}")
println("")
// ==================
// @arrays library
// ==================
println("-- @arrays --")
temp nums [int] = {1, 2, 3, 4, 5}
println("nums = ${nums}")
println("arrays.first(nums) = ${arrays.first(nums)}")
println("arrays.last(nums) = ${arrays.last(nums)}")
println("arrays.reverse(nums) = ${arrays.reverse(nums)}")
println("arrays.slice(nums, 1, 4) = ${arrays.slice(nums, 1, 4)}")
println("arrays.contains(nums, 3) = ${arrays.contains(nums, 3)}")
println("")
temp grow [int] = {10, 20}
arrays.append(grow, 30)
println("After arrays.append(grow, 30): ${grow}")
temp last int = arrays.pop(grow)
println("arrays.pop() returned ${last}, grow = ${grow}")
println("")
// ==================
// @maps library
// ==================
println("-- @maps --")
temp scores map[string:int] = {"alice": 95, "bob": 87, "charlie": 92}
println("scores = ${scores}")
println("maps.keys(scores) = ${maps.keys(scores)}")
println("maps.values(scores) = ${maps.values(scores)}")
temp alice_key string = "alice"
temp diana_key string = "diana"
temp has_alice bool = maps.has(scores, alice_key)
temp has_diana bool = maps.has(scores, diana_key)
println("maps.has(scores, 'alice') = ${has_alice}")
println("maps.has(scores, 'diana') = ${has_diana}")
println("")
// ==================
// @time library
// ==================
println("-- @time --")
println("time.now() = ${time.now()}")
println("time.year() = ${time.year()}")
println("time.month() = ${time.month()}")
println("time.day() = ${time.day()}")
println("time.hour() = ${time.hour()}")
println("time.minute() = ${time.minute()}")
println("time.second() = ${time.second()}")
}