Zebra: Common Patterns Reference
Copy-paste patterns for typical programming tasks.
File Operations
Read Entire File Safely
File.read/File.write are not throws — a missing file panics rather
than raising, so guard with File.exists() first:
if not File.exists("data.txt")
print("Cannot read file")
else
var content = File.read("data.txt")
print(content)
Write File Safely
def write_output()
File.write("output.txt", "File contents here")
print("File written successfully")
Process File Line by Line
var content = File.read("file.txt")
var lines = content.split("\n")
for line in lines
if line.trim().len == 0
continue # Skip empty lines
# Process line...
print(line)
Read CSV File
var content = File.read("data.csv")
var lines = content.split("\n")
var records = List(List(str))()
for line in lines
if line.trim().len == 0
continue
var fields = line.split(",")
records.add(fields)
for record in records
print(record) # Each field: record.at(0), record.at(1), etc.
String Processing
Split and Process Words
var text = "one two three four five"
var words = text.split(" ")
for word in words
print("Word: ${word}")
Build String from Parts
var parts = List(str)()
parts.add("hello")
parts.add("world")
parts.add("from")
parts.add("zebra")
var message = parts.join(" ") # "hello world from zebra"
Find and Replace
var text = "Hello World Hello"
# Replace every occurrence (replaceAll is the same call, spelled out)
var result1 = text.replace("Hello", "Hi") # "Hi World Hi"
var result2 = text.replaceAll("Hello", "Hi") # "Hi World Hi"
# Find position
var pos = text.indexOf("World")
if pos >= 0
print("Found at position ${pos}")
Extract Substring
var text = "Hello, World!"
var greeting = text.substring(0, 5) # "Hello"
var after_comma = text.substring(7, 12) # "World"
Clean Input
var user_input = " hello world \n"
var clean = user_input.trim() # "hello world"
Case Conversion
var text = "Hello World"
var upper = text.upper() # "HELLO WORLD"
var lower = text.lower() # "hello world"
Collections & Lists
Create and Populate List
var numbers = List(int)()
numbers.add(1)
numbers.add(2)
numbers.add(3)
Loop Over List
for item in items
print(item)
# With index
for i in 0.to(items.count())
print("${i}: ${items.at(i)}")
Find Item in List
var target = "apple"
for item in items
if item == target
print("Found it!")
break
Filter List
var numbers = List(int)()
numbers.add(1)
numbers.add(2)
numbers.add(3)
numbers.add(4)
numbers.add(5)
var evens = List(int)()
for num in numbers
if num % 2 == 0
evens.add(num)
# evens = [2, 4]
Transform List
var numbers = List(int)()
numbers.add(1)
numbers.add(2)
numbers.add(3)
var doubled = List(int)()
for num in numbers
doubled.add(num * 2)
# doubled = [2, 4, 6]
Remove Duplicates
var items = List(str)()
items.add("apple")
items.add("banana")
items.add("apple")
items.add("cherry")
var seen = HashMap(str, bool)()
var unique = List(str)()
for item in items
if not seen.contains(item)
seen.put(item, true)
unique.add(item)
# unique has: apple, banana, cherry (duplicates removed)
Count Occurrences
var items = List(str)()
items.add("apple")
items.add("apple")
items.add("banana")
var count = 0
for item in items
if item == "apple"
count = count + 1
print(count) # 2
Dictionaries & Maps
Create and Use HashMap
var scores = HashMap(str, int)()
scores.put("Alice", 95)
scores.put("Bob", 87)
scores.put("Charlie", 92)
var alice_score = scores.get("Alice")
if alice_score != nil
print("Alice: ${alice_score}")
Loop Over HashMap
for key, value in scores
print("${key}: ${value}")
Check if Key Exists
if scores.contains("Alice")
print("Alice found")
else
print("Alice not found")
Count by Category
var items = List(str)()
items.add("red")
items.add("blue")
items.add("red")
items.add("blue")
items.add("red")
var counts = HashMap(str, int)()
for item in items
var current = counts.get(item)
if current != nil
counts.put(item, current + 1)
else
counts.put(item, 1)
# counts: red->3, blue->2
Error Handling
Safe Function that Can Fail
def divide(a: int, b: int): int throws
if b == 0
raise "Cannot divide by zero"
return a / b
def attempt_divide()
var v = divide(10, 0)
print(v)
catch |err|
print("Error: ${err.message}")
class Main
static
def main
var value = divide(10, 2) catch 0
print("Result: ${value}")
attempt_divide()
Propagate Errors Up
def process_file(filename: str): int throws
var content = File.read(filename)
var line_count = content.split("\n").count()
return line_count
Handle Multiple Errors
def calculate(a_str: str, b_str: str): int throws
var a = a_str.tryInt()
if a == nil
raise "Invalid first number"
var b = b_str.tryInt()
if b == nil
raise "Invalid second number"
return a + b
Try Multiple Operations
def process_data() throws
# Step 1
var input = File.read("input.txt")
# Step 2: Process
var processed = input.upper()
# Step 3
File.write("output.txt", processed)
Null Safety
Safe Null Check
var x: int? = get_value()
if x != nil
print("Value: ${x}")
else
print("No value")
Use Default Value
var x: int? = get_value()
var value = x orelse 0 # Use 0 if nil
print(value)
Optional Chain
var user: User? = get_user()
if user != nil
if user.address != nil
print(user.address)
Nested Null Checks
var data: Data? = fetch_data()
if data != nil
var items = data.items
if items != nil
for item in items
print(item)
Type Conversions
String to Number
var num_str = "42"
var num = num_str.tryInt()
if num != nil
print(num + 1)
else
print("Invalid number")
Number to String
var num = 42
var text = num.toString()
var message = "The answer is ${text}"
String Interpolation (Preferred)
var num = 42
print("The answer is ${num}")
Type Checking
var value = 42
# Check if it's an int
var as_str = value.toString() # Force conversion
# Check compatibility
if value > 0
print("Positive")
Classes & Objects
Create Class with Constructor
class Person
var name: str = ""
var age: int = 0
cue init(name: str, age: int)
this.name = name
this.age = age
def describe(): str
return "${name} is ${age} years old"
var person = Person("Alice", 30)
print(person.describe())
Use Interfaces
interface Animal
def speak(): str
class Dog implements Animal
var name: str = ""
def speak(): str
return "Woof!"
var dog = Dog()
dog.name = "Buddy"
print(dog.speak())
Implement Interface
interface Shape
def area(): float
class Circle implements Shape
var radius: float = 0.0
def area(): float
return 3.14159 * radius * radius
var circle = Circle()
circle.radius = 5.0
print(circle.area())
Static Methods
class Math
static
def add(a: int, b: int): int
return a + b
var result = Math.add(2, 3) # 5
Make a Class a Value (print, ==, keys, sort)
Cues are the methods the compiler calls (Chapter 07, "Cues"). Without
them, == on a class is identity, a Set or HashMap keys it by
identity, and sort() does not build.
class Point
var x: int
var y: int
cue init(x: int, y: int)
.x = x
.y = y
cue toString(): str
return "(${.x}, ${.y})"
cue equals(other: Point): bool
return .x == other.x and .y == other.y
cue hash(): int # hash the fields equals compares
return .x * 31 + .y
cue compare(other: Point): int # by x, then by y
if .x != other.x
return .x - other.x
return .y - other.y
def main()
var visited: Set(Point) = Set()
visited.add(Point(1, 2))
visited.add(Point(1, 2))
print(visited.count()) # 1
var path = [Point(3, 0), Point(1, 2), Point(1, 1)]
path.sort()
print(path.at(0)) # (1, 1)
Regular Expressions
Validate Pattern
var email_pattern = Regex.compile("[a-z0-9]+@[a-z]+\\.[a-z]+")
if email_pattern.match("user@example.com")
print("Valid email")
Find Matches
var numbers = Regex.compile("\\d+")
var text = "I have 3 apples and 7 oranges"
var matches = numbers.findAll(text)
# matches = ["3", "7"]
for match in matches
print(match)
Split by Pattern
var delimiter = Regex.compile("\\s+") # One or more spaces
var text = "one two three"
var words = delimiter.split(text)
# words = ["one", "two", "three"]
Replace Pattern
var pattern = Regex.compile("\\d+")
var text = "Version 2.3.1"
var replaced = pattern.replace(text, "X") # every match
# replaced = "Version X.X.X"
Command-Line Arguments
Read Arguments
class Main
static
def main
var args = sys.args()
if args.count() > 0
print("Arguments:")
for arg in args
print(" - ${arg}")
else
print("No arguments provided")
Parse Flags
class Main
static
def main
var args = sys.args()
var verbose = false
var input_file = ""
for arg in args
if arg == "-v" or arg == "--verbose"
verbose = true
else if arg.startsWith("--input=")
input_file = arg.substring(8, arg.len)
print("Verbose: ${verbose}")
print("Input: ${input_file}")
Environment Variables
Environment and Exit
# Exit with status code
sys.exit(1)
# Use Arg for structured argument parsing
var result = Arg.parse()
Loops & Iteration
Count Loop
for i in 0.to(10)
print(i) # 0, 1, 2, ..., 9
While Loop
var i = 0
while i < 10
print(i)
i = i + 1
Loop Until Condition
var count = 0
while count < 5
print(count)
count = count + 1
Early Exit
for item in items
if item == target
print("Found!")
break
while condition
if error_detected
break
Skip Iteration
for item in items
if item == skip_value
continue
print(item)
Lazy Sequence (Generator)
A def returning Iter(T) produces values one yield at a time, so the
caller can stop early and nothing is collected first (Chapter 05,
"Generators"). For your own iterable class, see cue iter / cue next
in Chapter 07.
def readTokens(text: str): Iter(str)
var parts: List(str) = text.split(",")
for p in parts
var t = p.trim()
if t.len > 0
yield t
def main()
for tok in readTokens("a, b,, c")
print(tok) # a, b, c (one per line)
Practical Patterns
CSV Reader
def read_csv(filename: str): List(List(str)) throws
var content = File.read(filename)
var lines = content.split("\n")
var records = List(List(str))()
for line in lines
if line.trim().len == 0
continue
var fields = line.split(",")
records.add(fields)
return records
Word Counter
def count_words(filename: str): HashMap(str, int) throws
var content = File.read(filename)
var text = content.lower()
var words = text.split(" ")
var counts = HashMap(str, int)()
for word in words
var clean = word.trim()
if clean.len > 0
var current = counts.get(clean)
if current != nil
counts.put(clean, current + 1)
else
counts.put(clean, 1)
return counts
Pipeline Processing
The -> pipeline operator's right-hand side must be a call to a free
function (x -> f(), meaning f(x)) — it can't take a .method() on its
own, and it doesn't span multiple lines. For chaining methods on a value,
just chain the method calls directly:
var input = " hello world from zebra "
var result = input.trim().lower().split(" ")
# result is a List(str); note double spaces in the input produce empty
# elements between words, since split(" ") is a raw split
Quick Debugging
Print Variable Value
var x = 42
print("x = ${x}")
Check Collection Size
var items = List(int)()
items.add(1)
items.add(2)
print("Count: ${items.count()}")
Trace Execution
def function()
print("Start")
# ... code ...
print("After step 1")
# ... code ...
print("Done")
Assert Conditions
assert x > 0, "x must be positive"
assert items.count() > 0, "list must not be empty"
Save this page and copy patterns as needed!