Part 5: Ecosystem (Chapters 19-22)
Chapter 19: Standard Library Tour
Time: 90 min | Prereq: 01-06
Overview
Explore what's available before writing your own utilities.
Core Modules
String Methods:
.len— length.upper(),.lower()— case.split(),.join()— partition/combine.trim(),.trimLeft(),.trimRight()— whitespace.contains(),.startsWith(),.endsWith()— search.replace(),.replaceAll()— substitution.charAt(),.substring(),.indexOf()— access.concat()— combine.reverse()— flip
Collection Methods:
List.add(),List.remove(),List.count(),List.at()HashMap.put(),HashMap.fetch(),HashMap.contains()Set.add(),Set.remove(),Set.contains()- Iteration:
for item in collection
Math Functions:
- Arithmetic: +, -, *, /, %
- Comparison: <, >, <=, >=, ==, !=
- Logical: and, or, not
- Type conversion:
.toString(),.toInt(),.toFloat()
Real World
Learning what exists prevents reinventing wheels.
Chapter 20: File I/O and System Access
Time: 90 min | Prereq: 06, 12
File Operations
class FileIO
static
def read_file(path: str): str
# File.read is not `throws`: a missing file stops the program
if not File.exists(path)
return ""
return File.read(path)
def write_file(path: str, content: str)
File.write(path, content)
def file_exists(path: str): bool
return File.exists(path)
def delete_file(path: str)
File.delete(path) # a no-op if the file is missing
Line-by-Line Reading
class LineReader
static
def process_lines(path: str): int
var lines = 0
var content = if(File.exists(path), File.read(path), "")
for line in content.split("\n")
if line.len > 0
lines = lines + 1
return lines
System Access
class System
static
def args(): List(str)
return sys.args() # args.at(0) is the program itself
def env(name: str): str?
return sys.getenv(name) # nil if the variable is not set
def cwd(): str
return sys.cwd()
Key Topics
- Text file reading/writing
- Binary files
- Directory operations
- Error handling for file not found
- Line-by-line processing
- CSV/JSON parsing basics
Chapter 21: Regular Expressions (Deep Dive)
Time: 90 min | Prereq: 06
Regex Pattern Syntax
Literals:
hello— exact matchh.llo— . matches any charh*llo— * = zero or moreh+llo— + = one or moreh?llo— ? = zero or one
Classes:
[abc]— any of a, b, c[a-z]— range a through z[^abc]— NOT a, b, c\d— digit\w— word char\s— whitespace
Anchors:
^hello— start of linehello$— end of line\bhello\b— word boundary
Groups:
(hello|hi)— alternation(ab)+— repeat group
Common Patterns
# Email
var email_re = Regex.compile("[a-z0-9]+@[a-z]+\\.[a-z]+")
# Phone
var phone_re = Regex.compile("\\d{3}-\\d{3}-\\d{4}")
# URL
var url_re = Regex.compile("https?://[a-z0-9]+\\.[a-z]+")
Operations
class RegexOps
static
def matches(re: Regex, text: str): bool
return re.match(text) # the WHOLE text must match
def find(re: Regex, text: str): str
return re.find(text) # "" when there is no match
def findAll(re: Regex, text: str): List(str)
return re.findAll(text)
def replace(re: Regex, text: str, replacement: str): str
return re.replace(text, replacement) # replaces every match
def split(re: Regex, text: str): List(str)
return re.split(text)
Real-World Use Cases
- Email/phone validation
- Log parsing
- Data extraction
- Text normalization
Chapter 22: FFI and Interop
Time: 90 min | Prereq: 02, 07, 12
Calling C Code
class CInterop
static
def c_add(a: int, b: int): int
# Call C function
return a + b
def c_strlen(s: str): int
# Call strlen from C stdlib
return 0
Calling Zig Code
class ZigInterop
static
def zig_sqrt(x: float): float
# Call Zig function
return 0.0
def zig_random(): int
# Call Zig's random
return 0
Type Marshaling
# Sketch -- c_func would be declared with `extern` (see Chapter 22).
# C expects: int foo(const char* str, int* out_len)
# Zebra code:
def call_c_func(input: str): int
var out_len: int = 0
var result = c_func(input, out_len)
return out_len
Safety Considerations
- Memory ownership
- Lifetime issues
- Type compatibility
- Error handling across boundaries
Real-World Applications
- Calling system libraries
- Performance-critical code
- Platform-specific features
- Legacy code integration
Appendices
Appendix A: Grammar Reference
Types:
- Primitives:
int,float,bool,str,char - Collections:
List(T),HashMap(K,V),Set(T) - Nullable:
T?(can be T or nil) - Fallible functions:
def f(): T throws(there is noResulttype)
Classes:
class Name
var field: Type = default
static
def static_method()
def instance_method()
Interfaces:
interface Name
def method_signature()
Functions:
def function_name(param: Type): ReturnType
return value
Control Flow:
if condition ... elif ... else ...while condition ... break ... continuefor item in collection ...branch value on case ...
Appendix B: Built-in Functions and Stdlib
I/O:
print(value)— output to console, followed by a newlineFile.read(path)— read fileFile.write(path, content)— write file
Type Conversion:
.toString()— to string.toInt()— to integer.toFloat()— to float
Collections:
List.add(),List.remove(),List.count()HashMap.put(),HashMap.fetch(),HashMap.contains()Set.add(),Set.remove(),Set.contains()
String Methods: (See Chapter 19 for comprehensive list)
System:
sys.args()— command-line argumentssys.errln(msg)— error outputFile.exists(path),File.delete(path)
Appendix C: Troubleshooting
"error: arithmetic requires numeric type, got 'str'"
→ Can't use + with strings. Use .concat() or interpolation: "${var}"
"error: use of undefined identifier 'nil'"
→ Variable type isn't nullable. Use T? not T if it can be nil.
"error: cannot assign to immutable value"
→ You assigned to something that cannot change (for example a const). Declare it with var, or add a setter method
"error: nil pointer"
→ You force-unwrapped nil with !. Check before unwrapping: if x != nil
"error: unimplemented interface method" → Your class doesn't implement all interface methods. Add the missing method.
Performance tips:
- Use StringBuilder for loop concatenation
- Lazy-load expensive resources
- Cache computed properties
- Avoid deep copying large structures
Quick Reference
Common Tasks:
# Read file
var content = File.read("file.txt")
# Parse lines
var lines = content.split("\n")
# Count items
for item in items
count = count + 1
# Search list
for item in items
if item.contains("search")
print(item)
# Convert types
var num = "42".toInt()
# Handle nil
var value: str? = get_value()
if value != nil
print(value)
# Handle errors (operation is a `throws` function)
var result = operation() catch "fallback"
print(result)
Where to Go Next
- Build the three projects
- Contribute to Zebra itself
- Share projects on GitHub
- Write your own libraries
You've completed the Zebra programming guide. Welcome to the community!