The language in use
Zhex, by example.
Read every program, see its output, and run it yourself.
Runnable examples are compiled to WebAssembly and run entirely in your browser, using WebAssembly garbage collection — roughly Chrome 119+, Firefox 120+, or Safari 18.2+.
Language basics
Small programs for learning Zhex values, words, and effects.
Console input
Read a name, transform the value, and print a greeting.
word greet(name: String) -> String
"Hello, " + name + "!"
let name = read-line "Your name: " try
flow name
greet
print
Run
zhex run examples/hello.zhexOne line of text
Output
Your name: Hello, Ada!
Composition
Build larger operations from small typed words.
word square(n: Int) -> Int
let result = n * n
result
word double(n: Int) -> Int
n + n
flow 4
square
double
print
Run
zhex run examples/composition.zhexOutput
32
With blocks
Fix one seed value and apply many operations to it.
## A with block fixes one seed value: every step receives the seed as
## its first argument, never the previous step's result, and the last
## step's value is the block's value.
let name = "zhex"
let shout = flow name
with text
upper
length
slice 1, 3
print(shout)
let values = [1, 2]
let kept = values
with list
append(3)
length
print(kept)
Run
zhex run examples/with-blocks.zhexOutput
he 3
Calls and defaults
Call words with or without parentheses and compose them in flows.
word greet name: String = "Ada"
"Hello, " + name
word add(left: Int, right: Int) -> Int
left + right
word seven
7
let default-greeting = greet
let named-greeting = greet "Grace"
let parenthesized-sum = add(1, 2)
let bare-sum = add 1, 2
let answer = seven
print default-greeting
print named-greeting
print parenthesized-sum
print bare-sum
print answer
print 1 + 1
print(add(-1, 2))
let values = [8, 5]
print(values[0] - values[1])
Run
zhex run examples/calls.zhexOutput
Hello, Ada Hello, Grace 3 3 7 2 1 3
Not compiled to WebAssembly yet — word parameter defaults is not available in this build.
Word defaults
Use inferred parameter defaults and fresh values for each call.
word default-name()
print("default ran")
"Ada"
word greet(prefix: String, name = default-name())
prefix + " " + name
word append-one(values: List<Int> = [])
list.append(values, 1)
list.length(values)
print(greet("Hello", "Grace"))
print(greet("Hello"))
print(append-one())
print(append-one())
Run
zhex run examples/word-defaults.zhexOutput
Hello Grace default ran Hello Ada 1 1
Not compiled to WebAssembly yet — word parameter defaults is not available in this build.
Explicit partial application
Capture arguments with holes, then call the resulting word value.
word add left: Int, right: Int -> Int
left + right
let plus-five = add _, 5
let five-plus: (Int) -> Int = add 5, _
print plus-five(7)
let right-hole-result = five-plus 7
print right-hole-result
var offset = 5
let plus-offset = add _, offset
offset = 100
let captured-result = plus-offset 7
print captured-result
word append-and-count(item: Int, values: List<Int> = []) -> Int
list.append(values, item)
list.length(values)
let add-to-fresh-list = append-and-count _
print add-to-fresh-list(1)
let second-length = add-to-fresh-list 2
print second-length
flow 7
plus-five
print
let change = text.replace _, "A", "a"
print(change("ADA"))
let show: (Int) -> Unit = print _
show 7
let append-one = list.append _, 1
let values: List<Int> = []
append-one(values)
print(list.length(values))
word parse raw: String
text.to-int raw try
let parse-later = parse _
let parsed = parse-later "8" try
print parsed
let fallback = parse-later "bad" catch problem
print(error.code(problem))
3
print fallback
Run
zhex run examples/partials.zhexOutput
12 12 12 1 1 12 aDa 7 1 8 text-to-int 3
Not compiled to WebAssembly yet — word parameter defaults is not available in this build.
Named records
Group related values in a checked named type.
# A record gives related values one checked, named type.
type Customer = record
name: String
age: Int
word customer-summary(customer: Customer) -> String
customer.name + ", age " + int.to-string(customer.age)
let ada: Customer = Customer("Ada", 36)
print(customer-summary(ada))
Run
zhex run examples/records.zhexOutput
Ada, age 36
Choices and matching
Select and handle alternatives with a checked match.
type Status = choice
Pending
Running
Failed(message: String)
word describe(status: Status) -> String
match status
case Status.Pending
"pending"
case Status.Running
"running"
case Status.Failed(message)
"failed: " + message
print(describe(Status.Running))
match Status.Failed("network unavailable")
case Status.Failed(message)
print "Could not start: " + message
case _
print "No failure"
type Maybe<T> = choice
None
Some(value: T)
let answer = Maybe.Some(7)
let empty: Maybe<Int> = Maybe.None
word maybe-value(m: Maybe<Int>) -> Int
match m
case Maybe.Some(value)
value
case Maybe.None
0
print(maybe-value(answer))
print(maybe-value(empty))
Run
zhex run examples/choices.zhexOutput
running Could not start: network unavailable 7 0
Not compiled to WebAssembly yet — generic choice Maybe is not available in this build.
Lists and arrays
Build and safely iterate lists and rectangular arrays.
# Lists grow by append; select keeps the elements a predicate accepts; arrays are rectangular, select whole rows, and keep overlapping values on resize.
word short(name: String) -> Bool
text.length(name) < 5
word big-first(row: List<Int>) -> Bool
row[0] > 1
let names: List<String> = ["Ada", "Grace"]
list.append(names, "Lin")
print(list.length(names))
print names[1]
let grown = flow [1]
list.append(2)
list.append(3)
print(list.length(grown))
let alias = names
for index, name in names
print(int.to-string(index) + ": " + name)
let blocked = list.append(alias, "blocked") catch problem
print(error.code(problem))
alias
let short-names = list.select(names, short(_))
print(list.length(short-names))
print(short-names[1])
let grid: Array<Int> = array.new([2, 3], 0)
grid[0, 0] = 1
grid[0, 1] = 2
grid[0, 2] = 3
grid[1, 0] = 4
grid[1, 1] = 5
grid[1, 2] = 6
let big-rows = array.select(grid, big-first(_))
print(array.shape(big-rows)[0])
print(big-rows[0, 1])
for coordinates, value in grid
let row = coordinates[0]
let column = coordinates[1]
print(int.to-string(row) + "," + int.to-string(column) + ": " + int.to-string(value))
array.resize(grid, [3, 4], 7)
print(grid[1, 2])
print(grid[2, 3])
print(array.length(grid))
Run
zhex run examples/collections.zhexOutput
3 Grace 3 0: Ada collection-iterating 1: Grace collection-iterating 2: Lin collection-iterating 2 Lin 1 5 0,0: 1 0,1: 2 0,2: 3 1,0: 4 1,1: 5 1,2: 6 6 7 12
Not compiled to WebAssembly yet — checked list.append is not available in this build.
Dates and time zones
Compare calendar days with elapsed time across a daylight-saving transition.
# A calendar day and 24 elapsed hours differ across a daylight-saving change.
let zone = timezone.load "America/New_York" try
let start = zoned.new(date.new(2024, 3, 9), time.new(12, 0, 0), zone)
let elapsed = duration.parse "24h" try
print(zoned.to-string(zoned.add-days(start, 1)))
print(zoned.to-string(zoned.add-duration(start, elapsed)))
Run
zhex run examples/temporal.zhexOutput
2024-03-10T12:00:00-04:00[America/New_York] 2024-03-10T13:00:00-04:00[America/New_York]
Not compiled to WebAssembly yet — timezone.load is not available in this build.
Typed JSON configuration
Decode configuration with typed defaults and encode it again.
type Settings = record
retries: Int = 3
verbose: Bool = false
let settings = json.decode(
"{\"verbose\":true}",
Settings(verbose: true)
) try
print settings.retries
print settings.verbose
print(json.encode(settings) try)
Run
zhex run examples/json-config.zhexOutput
3
true
{"retries":3,"verbose":true}
Not compiled to WebAssembly yet — record field defaults is not available in this build.
JSON trees
Parse a heterogeneous payload into a Json tree, walk it recursively, and encode it back.
# A heterogeneous payload with mixed-type arrays and dynamic keys, held in
# the host-owned Json tree type.
let raw = "{ \"service\": \"ingest\", \"retries\": 1.5e1, \"endpoints\": [ \"primary\", 443, null, { \"host\": \"db\", \"port\": 5432 } ], \"flags\": { \"dry-run\": true } }"
word count-nodes(doc: Json) -> Int
match doc
case Json.List(values)
var total = 1
for v in values
total = total + count-nodes(v)
total
case Json.Object(fields)
var total = 1
for key, value in fields
total = total + count-nodes(value)
total
case _
1
word label(doc: Json) -> String
match doc
case Json.Null
"null"
case Json.Bool(value)
if value
"true"
else
"false"
case Json.Text(value)
value
case Json.Number(literal)
literal
case Json.List(values)
"list of " + int.to-string(list.length(values))
case Json.Object(fields)
"object of " + int.to-string(map.length(fields))
let doc = json.parse(raw) try
print("nodes: " + int.to-string(count-nodes(doc)))
match doc
case Json.Object(fields)
for key, value in fields
print(key + " = " + label(value))
case _
print("unexpected shape")
# encode(parse(raw)) keeps key order and number literals byte-for-byte and
# normalizes whitespace to compact form.
print(json.encode(doc) try)
Run
zhex run examples/json-tree.zhexOutput
nodes: 12
service = ingest
retries = 1.5e1
endpoints = list of 4
flags = object of 1
{"service":"ingest","retries":1.5e1,"endpoints":["primary",443,null,{"host":"db","port":5432}],"flags":{"dry-run":true}}
Typed XML configuration
Decode an embedded XML document with attribute fields, a list of endpoint records, and an optional owner.
type Endpoint = record
host: String
port: Int
type Service = record
name: String
retries: Int
dry-run: Bool
endpoints: List<Endpoint>
owner: Option<String>
let config = "<service retries=\"3\" dry-run=\"true\"><name>ingest</name><endpoints><host>db</host><port>5432</port></endpoints><endpoints><host>web</host><port>443</port></endpoints></service>"
let service = xml.decode(
config,
Service("backup", 1, false, [], Option.None)
) try
print service.name
print service.retries
print service.dry-run
print(list.length(service.endpoints))
let primary = service.endpoints[0] try
print(primary.host + ":" + int.to-string(primary.port))
match service.owner
case Option.None
print("owner unset")
case Option.Some(owner)
print("owner " + owner)
Run
zhex run examples/xml-config.zhexOutput
ingest 3 true 2 db:5432 owner unset
Maps and lookup
Store keyed values, match optional lookups, and merge maps.
let scores = {"Ada": 10, "Grace": 9}
let empty: Map<String, Int> = {}
flow empty
map.put("Iris", 8)
map.length
print
scores["Ada"] = 11
flow scores
map.put("Nancy", 23)
map.length
print
match scores["Ada"]
case Option.Some(score)
print("Ada: " + int.to-string(score))
case Option.None
print("Ada has no score")
match scores["Morgan"]
case Option.Some(score)
print("Morgan: " + int.to-string(score))
case Option.None
print("Morgan has no score")
for name, score in scores
print(name + ": " + int.to-string(score))
flow {"Lin": 12}
map.into scores
map.length
print
map.remove(scores, "Missing")
print(map.length(scores))
Run
zhex run examples/maps.zhexOutput
1 3 Ada: 11 Morgan has no score Ada: 11 Grace: 9 Nancy: 23 4 4
Error recovery
Catch invalid numeric input and continue with a useful fallback.
let rawRetries = "abc"
let retries = text.to-int rawRetries catch
print "That is not a whole number. I'll use 3 retries."
3
print("Retries: " + int.to-string(retries))
Run
zhex run examples/recovery.zhexOutput
That is not a whole number. I'll use 3 retries. Retries: 3
Exit status
Choose a valid status; invalid input exits with status 2.
# Use console.exit to choose a portable process status.
let line = read-line "Exit status (0..255): " try
let status = text.to-int line catch problem
print("Invalid status: " + error.code(problem))
console.exit(2)
if status < 0 or status > 255
print "Status must be from 0 to 255."
console.exit(2)
print("Exiting with status " + int.to-string(status))
console.exit(status)
Run
zhex run examples/exit-status.zhexSample input
0
Output
Exit status (0..255): Exiting with status 0
Not compiled to WebAssembly yet — error.code is not available in this build.
Text statistics
Read a file two ways: whole-buffer counts and a streamed uppercased echo.
# Report line, word, and character counts for a text file.
# One argument counts the whole file; a second argument streams it uppercased.
let path = console.arg 0 try
if console.args-count() == 1
let body = file.read path try
print(int.to-string(text.line-count(body)) + " lines " + int.to-string(text.word-count(body)) + " words " + int.to-string(text.length(body)) + " chars")
else
for line in file.stream(path)
print(text.upper(line))
Run
zhex run examples/text-stats.zhex examples/text-stats-sample.txtOutput
3 lines 11 words 64 chars
Not compiled to WebAssembly yet — console.arg is not available in this build.
Line filter
Split embedded records, select them by literal prefix and suffix, and join a report.
# Select records by literal prefix and suffix, then join the selected fields.
# Split keeps every field as-is; only lines matching both checks reach the report.
let records = "inv-1042;paid\ninv-1043;due\ninv-1044;paid\nquote-77;paid"
let shipped: List<String> = []
for line in text.split(records, "\n")
if text.starts-with(line, "inv-") and text.ends-with(line, "paid")
let added = list.append(shipped, text.split(line, ";")[0])
print("shipped: " + text.join(shipped, ", "))
Run
zhex run examples/line-filter.zhexOutput
shipped: inv-1042, inv-1044
Score report
Trim and score embedded records with list map, filter, fold, find, any, and all.
# Trim and score embedded records with the list words: map, filter, fold, find, any, all.
word add left: Int, right: Int -> Int
left + right
word score entry: String -> Int
let raw = text.split(entry, ": ")[1]
text.to-int raw catch
print("unreadable score in: " + entry)
0
word above threshold: Int, value: Int -> Bool
value > threshold
let raw = "Ada: 36, Grace: 9, Lin: 41, Nancy: 23"
let names = flow text.split(raw, ",")
list.map(text.trim(_))
text.join(" / ")
print names
let scores = flow text.split(raw, ",")
list.map(text.trim(_))
list.map(score(_))
let passing = list.filter(scores, above(20, _))
print("passing: " + int.to-string(list.length(passing)) + " of " + int.to-string(list.length(scores)))
print("total: " + int.to-string(list.fold(passing, 0, add(_, _))))
match list.find(scores, above(40, _))
case Option.Some(first)
print("first above 40: " + int.to-string(first))
case Option.None
print("nobody above 40")
if list.any(scores, above(40, _)) and not list.all(scores, above(40, _))
print("someone is above 40, but not everyone")
Run
zhex run examples/score-report.zhexOutput
Ada: 36 / Grace: 9 / Lin: 41 / Nancy: 23 passing: 3 of 4 total: 100 first above 40: 41 someone is above 40, but not everyone
Sorting
Rank records with list.sort-by and a named key word, and sort plain text with list.sort.
# Rank records with list.sort-by and a named key word, sort plain text with list.sort; both leave the source untouched.
type Entry = record
name: String
score: Int
word score entry: Entry -> Int
entry.score
word entry-line entry: Entry -> String
entry.name + ": " + int.to-string(entry.score)
let entries = [Entry("Ada", 41), Entry("Grace", 23), Entry("Lin", 41), Entry("Nancy", 23)]
let ranked = list.sort-by(entries, score(_))
for entry in ranked
print(entry-line(entry))
print("source unchanged: " + entry-line(entries[0]))
let fruits = ["pear", "fig", "apple"]
print("sorted: " + text.join(list.sort(fruits), ", "))
Run
zhex run examples/sorting.zhexOutput
Grace: 23 Nancy: 23 Ada: 41 Lin: 41 source unchanged: Ada: 41 sorted: apple, fig, pear
File write
Attempt a checked report write and handle the failed Result with catch.
# Save a report with file.write; the host refuses to open a directory for
# writing, so catch handles the failed Result instead of crashing.
let report = "invoices: 2\ncredits: 7\n"
let saved = file.write(report, "/") catch problem
print("Save failed: " + error.code(problem))
print("Nothing was written; the report stays in memory.")
print("In-memory report:\n" + report)
Run
zhex run examples/file-write.zhexOutput
Save failed: file-write Nothing was written; the report stays in memory. In-memory report: invoices: 2 credits: 7
Not compiled to WebAssembly yet — error.code is not available in this build.
Lexical paths
Compose and decompose paths with file.join, base, extension, and directory-of.
# Compose and decompose paths lexically with the file path words; nothing
# here reads or writes the disk.
word report-path(folder: String, name: String) -> String
file.join(folder, name)
let invoice = report-path("/tmp/zhex-out", "june/invoices.csv")
print(invoice)
print(file.directory-of(invoice))
print(file.base(invoice))
print(file.extension(invoice))
# An absolute child replaces the base instead of nesting under it, and ..
# is cleaned lexically; no word checks the disk.
print(report-path("/tmp/zhex-out", "/var/run/state.json"))
print(report-path("/tmp/zhex-out", "../archive/old.csv"))
Run
zhex run examples/paths.zhexOutput
/tmp/zhex-out/june/invoices.csv /tmp/zhex-out/june invoices.csv .csv /var/run/state.json /tmp/archive/old.csv
File work folder
Create a work folder, write reports into it, inspect them, and remove the whole tree.
# Build a work folder, write reports into it, inspect what landed, and
# remove the whole tree — the file round trip in one program. The base
# folder is the first program argument.
let base = console.arg(0) try
let work = base + "/zhex-work"
# An interrupted earlier run may have left the folder behind; remove it so
# every run below is deterministic.
if file.exists(work)
file.delete-folder(work, true) try
file.make-folder(work, true) try
file.write("invoices: 2\n", work + "/invoices.txt") try
file.write("credits: 7\n", work + "/credits.txt") try
let names = file.list(work) try
print("work folder: " + text.join(names, ", "))
let bytes = file.size(work + "/invoices.txt") try
print("invoices.txt: " + int.to-string(bytes) + " bytes")
# The byte count is machine-dependent, so only the answer is printed.
if file.free-space(work) try > 0
print("volume still has space")
file.delete(work + "/invoices.txt") try
file.delete-folder(work, true) try
if file.exists(work)
print("work folder is still there")
else
print("work folder removed")
Run
zhex run examples/file-work.zhex .Output
work folder: credits.txt, invoices.txt invoices.txt: 12 bytes volume still has space work folder removed
Not compiled to WebAssembly yet — console.arg is not available in this build.
Env configuration
Write a .env fixture, load it, read settings back as options, and clean up.
# Configure a batch report from a .env file: write the fixture, load it,
# read each setting back as an Option, and clean up. The base folder is
# the first program argument.
let base = console.arg(0) try
let env-path = base + "/report.env"
file.make-folder(base, true) try
# The title appears twice; the first assignment wins, so the report keeps
# "Weekly status". An empty value after = is set, not missing.
file.write("ZHEX_REPORT_TITLE=Weekly status\nZHEX_REPORT_TITLE=Daily drudgery\nZHEX_REPORT_MODE=\n", env-path) try
env.load env-path try
match env.get("ZHEX_REPORT_TITLE")
case Option.Some(title)
print("title: " + title)
case Option.None
print("title: unset")
match env.get("ZHEX_REPORT_MODE")
case Option.Some(mode)
if mode == ""
print("mode: set but empty")
else
print("mode: " + mode)
case Option.None
print("mode: unset")
match env.get("ZHEX_REPORT_LIMIT")
case Option.Some(limit)
print("limit: " + limit)
case Option.None
print("limit: not in the file")
file.delete env-path try
print("report configured")
Run
zhex run examples/env-config.zhex .Output
title: Weekly status mode: set but empty limit: not in the file report configured
Not compiled to WebAssembly yet — console.arg is not available in this build.
Modules
Split a program across files: main imports a sibling math library.
# Two files, one program: main imports the math library beside it and
# composes its words, including a flow step.
use math
let a-line = read-line "First number: " try
let a = text.to-int a-line try
let b-line = read-line "Second number: " try
let b = text.to-int b-line try
if a <= 0 or b <= 0
print "Enter two positive integers."
else
flow a - b
math.abs
print
print(math.gcd(a, b))
print(math.lcm(a, b))
# A small math library. gcd and lcm share one helper that stays in this
# file: a leading underscore makes a word module-private.
## Absolute value of n.
## > abs(0 - 7)
## 7
## > abs(7)
## 7
word abs(n: Int) -> Int
if n < 0
0 - n
else
n
## Greatest common divisor of a and b.
## > gcd(12, 18)
## 6
## > gcd(7, 13)
## 1
word gcd(a: Int, b: Int) -> Int
if b == 0
a
else
gcd(b, a % b)
## Least common multiple of a and b.
## > lcm(4, 6)
## 12
## > lcm(3, 5)
## 15
word lcm(a: Int, b: Int) -> Int
_normalize(a * b) / gcd(a, b)
word _normalize(n: Int) -> Int
abs n
Run
zhex run examples/modules/main.zhexTwo numbers, one per line
Output
First number: Second number: 30 6 144
Module tests
Check a module's words from a .test.zhex file the zhex test runner discovers.
use math
use test
word test-gcd()
test.check(math.gcd(12, 18) == 6, "gcd(12, 18) should be 6")
test.check(math.gcd(7, 13) == 1, "coprimes collapse to 1")
test.check(math.gcd(0, 9) == 9, "zero falls through")
word test-abs()
test.check(math.abs(-5) == 5, "abs of a negative")
test.check(math.abs(5) == 5, "abs of a positive")
word test-to-int-fallback()
let n = text.to-int("not a number") catch
0
test.check(n == 0, "bad parse falls back to zero")
test-gcd()
test-abs()
test-to-int-fallback()
print "math module tests passed"
# A small math library. gcd and lcm share one helper that stays in this
# file: a leading underscore makes a word module-private.
## Absolute value of n.
## > abs(0 - 7)
## 7
## > abs(7)
## 7
word abs(n: Int) -> Int
if n < 0
0 - n
else
n
## Greatest common divisor of a and b.
## > gcd(12, 18)
## 6
## > gcd(7, 13)
## 1
word gcd(a: Int, b: Int) -> Int
if b == 0
a
else
gcd(b, a % b)
## Least common multiple of a and b.
## > lcm(4, 6)
## 12
## > lcm(3, 5)
## 15
word lcm(a: Int, b: Int) -> Int
_normalize(a * b) / gcd(a, b)
word _normalize(n: Int) -> Int
abs n
## Fails the run with its label when the condition is false.
word check(condition: Bool, label: String)
if not condition
console.fail label
Run
zhex run examples/modules/math.test.zhexOutput
math module tests passed
Not compiled to WebAssembly yet — console.fail is not available in this build.
Markdown report
Compose records and lists into a Markdown report through a pure-Zhex md module.
# A Markdown report from native values: the md module renders fragments,
# a Buffer accumulates them, and blank lines separate the blocks. The
# report stays in memory — printed as text, not written to a file, so the
# example's output is deterministic at build time.
use md
type Check = record
name: String
region: String
latency: Int
word check-row(check: Check) -> List<String>
[check.name, check.region, int.to-string(check.latency) + " ms"]
let checks = [
Check("edge-cache", "eu-west", 12),
Check("search-api (v2)", "eu-west", 41),
Check("auth", "us-east", 87)
]
let headers = ["service", "region", "latency"]
let rows = list.map(checks, check-row(_))
let report = flow buffer.new()
with buffer
add-line(md.heading(2, "Weekly status & latency"))
add-line("")
add-line(md.paragraph("Three services reported; nothing is down."))
add-line("")
add-line(md.table(headers, rows))
add-line("")
add-line(md.bullet-list(["no renderer", "no template engine, just words"]))
add-line("")
add-line(md.link("CommonMark", "https://commonmark.org/help"))
add-line("")
add-line(md.code-block("zhex", ["let title = md.heading(2, \"Weekly\")", "flow `inline code`", " text.upper"]))
to-text
print(report)
# A Markdown report library. Every word returns one String fragment and
# never touches a Buffer — the caller accumulates fragments and joins
# them with blank lines: text.join(fragments, "\n\n").
#
# Pinned contracts:
# - md.paragraph emits caller text verbatim apart from escaping; no
# trimming or rewrapping.
# - Text positions (headings, paragraphs, list items, table cells, link
# text) backslash-escape every ASCII CommonMark punctuation character;
# non-ASCII text passes through untouched.
# - Link targets always percent-encode spaces and parentheses; when the
# lowercased target starts with javascript: or data:, every colon is
# percent-encoded too, which renders the scheme inert.
# - md.code-block scans its lines for the longest backtick run and emits
# a fence of max(3, run + 1) backticks; nothing inside is escaped and
# the language tag is emitted verbatim after the opening fence.
# - md.heading clamps its level into 1..6.
# - md.table requires every row to match the header's cell count; the
# deliberate read past a mismatching row reports it as the interpreter's
# out-of-range diagnostic, so a malformed table never renders silently.
# - Empty input renders to the empty fragment "".
# - Dialect: CommonMark core subset; footnotes and task lists excluded.
word heading(level: Int, text: String) -> String
_repeat("#", _clamped(level)) + " " + _esc(text)
word paragraph(text: String) -> String
_esc(text)
word bullet-list(items: List<String>) -> String
var lines: List<String> = list.new()
for item in items
list.append(lines, "- " + _esc(item))
text.join(lines, "\n")
word ordered-list(items: List<String>) -> String
var lines: List<String> = list.new()
var n = 0
for item in items
n = n + 1
list.append(lines, int.to-string(n) + ". " + _esc(item))
text.join(lines, "\n")
word link(text: String, target: String) -> String
"[" + _esc(text) + "](" + _target(target) + ")"
word code-block(language: String, lines: List<String>) -> String
let mark = _repeat("`", _fence-length(lines))
if text.length(language) > 0
mark + language + "\n" + text.join(lines, "\n") + "\n" + mark
else
mark + "\n" + text.join(lines, "\n") + "\n" + mark
word table(headers: List<String>, rows: List<List<String>>) -> String
let width = list.length(headers)
# shortcut: strict rows — a row that misses or exceeds the header
# width is reported by the out-of-range read, upgrade: none.
for row in rows
if list.length(row) != width
let _short-or-long = row[list.length(row)]
let esc-headers = list.map(headers, _esc(_))
var esc-rows: List<List<String>> = list.new()
for row in rows
list.append(esc-rows, list.map(row, _esc(_)))
var widths: List<Int> = list.new()
for j in range(0, width)
var w = text.length(esc-headers[j])
for row in esc-rows
if text.length(row[j]) > w
w = text.length(row[j])
list.append(widths, w)
var lines: List<String> = list.new()
list.append(lines, _table-row(esc-headers, widths))
list.append(lines, _table-separator(widths))
for row in esc-rows
list.append(lines, _table-row(row, widths))
text.join(lines, "\n")
word _esc(text: String) -> String
flow text.split(text, "")
list.map(_esc-char(_))
text.join("")
word _esc-char(c: String) -> String
if text.contains("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~", c)
"\\" + c
else
c
word _target(t: String) -> String
let low = text.lower(t)
var out = text.replace(text.replace(text.replace(t, " ", "%20"), "(", "%28"), ")", "%29")
if text.starts-with(low, "javascript:") or text.starts-with(low, "data:")
out = text.replace(out, ":", "%3A")
out
word _repeat(ch: String, n: Int) -> String
var acc = ""
for _i in range(0, n)
acc = ch + acc
acc
word _clamped(level: Int) -> Int
if level < 1
1
elif level > 6
6
else
level
word _fence-length(lines: List<String>) -> Int
var longest = 0
for line in lines
let run = _longest-run(line)
if run > longest
longest = run
if longest >= 3
longest + 1
else
3
word _longest-run(line: String) -> Int
var best = 0
var run = 0
for c in text.split(line, "")
if c == "`"
run = run + 1
if run > best
best = run
else
run = 0
best
word _table-row(cells: List<String>, widths: List<Int>) -> String
var out = "|"
for j in range(0, list.length(cells))
out = out + " " + _padded(cells[j], widths[j]) + " |"
out
word _padded(cell: String, width: Int) -> String
var out = cell
for _i in range(text.length(cell), width)
out = out + " "
out
word _table-separator(widths: List<Int>) -> String
var out = "|"
for j in range(0, list.length(widths))
var n = 3
if widths[j] > 3
n = widths[j]
out = out + " " + _repeat("-", n) + " |"
out
Run
zhex run examples/modules/md-report/main.zhexOutput
## Weekly status \& latency
Three services reported\; nothing is down\.
| service | region | latency |
| ------------------ | -------- | ------- |
| edge\-cache | eu\-west | 12 ms |
| search\-api \(v2\) | eu\-west | 41 ms |
| auth | us\-east | 87 ms |
- no renderer
- no template engine\, just words
[CommonMark](https://commonmark.org/help)
```zhex
let title = md.heading(2, "Weekly")
flow `inline code`
text.upper
```
HTML page
Compose a page from the html module: text escapes by default, markup nests through element with one deliberate raw, and a javascript: link is rejected.
# A status page composed from the html module: text values are escaped,
# markup composes through element, and one javascript: link is rejected.
use html
# Each row introduces service text through escape-text; only the literal
# divider is deliberate markup and enters through html.raw.
word row(text: String) -> String
html.element("li", [], html.escape-text(text))
let rows = flow ["api: 2 ms", "web: 9 ms", "db: 41 ms & <degraded>"]
list.map(row(_))
text.join("\n")
let services = html.element("ul", [html.attr("class", "status \"live\" & <fresh>")], "\n" + rows + "\n")
let intro = html.element("p", [], html.escape-text("Everything below is escaped unless it arrives through html.raw."))
let divider = html.raw("<hr>")
let home = html.link("project home", "https://example.io/zhex") try
let blocked = html.link("run it", "javascript:alert(1)") catch
"(link rejected: javascript: is not an allowed scheme)"
print(html.page("Zhex services — café & <status>", intro + "\n" + services + "\n" + divider + "\n" + home + " / " + blocked))
# HTML composition with one rule: escaped unless raw. Text values are
# entity-escaped (&, <, >, ', ", matching Go's html.EscapeString) in every
# text position — escape-text, attribute values, link labels and targets,
# and the page title. Element content and the page body are composed
# markup: introduce text with escape-text, and mark deliberate literal
# markup with html.raw, the one bypass of every escaping property. The
# module never sanitizes HTML, CSS, or JavaScript.
# Entity-escape a text value for any position: & first so later entities stay literal.
word escape-text(value: String) -> String
flow value
text.replace("&", "&")
text.replace("<", "<")
text.replace(">", ">")
text.replace("'", "'")
text.replace("\"", """)
# One pre-escaped attribute; element joins these verbatim with spaces.
word attr(name: String, value: String) -> String
name + "=\"" + escape-text(value) + "\""
# unsafe: html.raw bypasses every escaping property; the module guarantee
# "escaped unless raw" does not hold past this call.
word raw(value: String) -> String
value
# One element; attributes come from attr, content is composed markup.
word element(tag: String, attributes: List<String>, content: String) -> String
let attrs = text.join(attributes, " ")
let head = "<" + tag
if attrs == ""
head + ">" + content + "</" + tag + ">"
else
head + " " + attrs + ">" + content + "</" + tag + ">"
# A complete minimal document: the title is text and is escaped; the body
# is composed markup emitted verbatim.
word page(title: String, body: String) -> String
("<!DOCTYPE html>\n<html>\n<head>\n<title>" + escape-text(title) + "</title>\n</head>\n<body>\n" + body + "\n</body>\n</html>")
# The URL policy for link targets: relative URLs and http, https, and
# mailto pass; any other scheme (javascript:, data:, ...) is rejected.
word _blocked(url: String) -> Bool
let lower = text.lower(url)
let colon = text.index-of(lower, ":")
if colon < 0
false
else
let scheme = text.slice(lower, 0, colon)
scheme != "http" and scheme != "https" and scheme != "mailto"
word link(label: String, href: String) -> Result<String, Error>
if _blocked(href)
err(error.new("html-url-scheme", "html.link allows only relative, http, https, and mailto URLs: " + href))
else
ok(element("a", [attr("href", href)], escape-text(label)))
Run
zhex run examples/modules/html-page/main.zhexOutput
<!DOCTYPE html> <html> <head> <title>Zhex services — café & <status></title> </head> <body> <p>Everything below is escaped unless it arrives through html.raw.</p> <ul class="status "live" & <fresh>"> <li>api: 2 ms</li> <li>web: 9 ms</li> <li>db: 41 ms & <degraded></li> </ul> <hr> <a href="https://example.io/zhex">project home</a> / (link rejected: javascript: is not an allowed scheme) </body> </html>
Not compiled to WebAssembly yet — error.new is not available in this build.
Algorithms
Complete programs that use those language tools to solve a problem.
FizzBuzz
Combine conditions, integer remainders, and a bounded loop.
word fizzbuzz(n: Int) -> String
if n % 15 == 0
"FizzBuzz"
elif n % 3 == 0
"Fizz"
elif n % 5 == 0
"Buzz"
else
int.to-string n
let limit-line = read-line "FizzBuzz up to (1..10000): " try
let limit = text.to-int limit-line try
if limit < 1 or limit > 10000
print "Enter a number from 1 to 10000."
else
for n in range(1, limit + 1)
flow n
fizzbuzz
print
Run
zhex run examples/fizzbuzz.zhexOne number
Output
FizzBuzz up to (1..10000): 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
Fibonacci
Use explicit mutable locals for an iterative algorithm.
word fibonacci(n: Int) -> Int
if n < 2
n
else
var previous = 0
var current = 1
for step in range(1, n)
let next = previous + current
previous = current
current = next
current
let index-line = read-line "Fibonacci index (0..92): " try
let index = text.to-int index-line try
if index < 0 or index > 92
print "Enter an index from 0 to 92."
else
flow index
fibonacci
print
Run
zhex run examples/fibonacci.zhexOne number
Output
Fibonacci index (0..92): 55
Factorial
Accumulate a result using a half-open integer range.
word factorial(n: Int) -> Int
var product = 1
for factor in range(1, n + 1)
product = product * factor
product
let number-line = read-line "Factorial of (0..20): " try
let number = text.to-int number-line try
if number < 0 or number > 20
print "Enter a number from 0 to 20."
else
flow number
factorial
print
Run
zhex run examples/factorial.zhexOne number
Output
Factorial of (0..20): 120
Times table
Iterate a bounded range and build output strings from integers.
# Print the times table for one number, from 1 to 10.
# A bounded loop that builds each line from integers.
let n-line = read-line "Table for: " try
let n = text.to-int n-line try
if n < 1 or n > 12
print "Enter a number from 1 to 12."
else
for i in range(1, 11)
print(int.to-string(n) + " x " + int.to-string(i) + " = " + int.to-string(n * i))
Run
zhex run examples/times-table.zhexOne number
Output
Table for: 7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 7 x 6 = 42 7 x 7 = 49 7 x 8 = 56 7 x 9 = 63 7 x 10 = 70
Palindrome
Compare text with its Unicode code-point reversal.
word is-palindrome(value: String) -> Bool
value == text.reverse(value)
let value = read-line "Text to check: " try
if is-palindrome(value)
print "Palindrome"
else
print "Not a palindrome"
Run
zhex run examples/palindrome.zhexOne line of text
Output
Text to check: Palindrome
Greatest common divisor
Recurse with Euclid's method and pipe a computed result through a flow.
# Greatest common divisor by Euclid's method.
# Recursion and a flow seeded with a computed call.
word gcd(a: Int, b: Int) -> Int
if b == 0
a
else
gcd(b, a % b)
let a-line = read-line "First number: " try
let a = text.to-int a-line try
let b-line = read-line "Second number: " try
let b = text.to-int b-line try
if a < 0 or b < 0
print "Enter two nonnegative integers."
else
flow gcd(a, b)
print
Run
zhex run examples/gcd.zhexTwo numbers, one per line
Output
First number: Second number: 6
Game of Life
Carry a finite grid through each generation in a flow; cells beyond the board are dead.
# Conway's Game of Life on a 7 by 7 board with a fixed-dead exterior.
word next-cell(grid: Array<Int>, row: Int, column: Int) -> Int
let current = grid[row, column]
var around = 0
for r in range(row - 1, row + 2)
for c in range(column - 1, column + 2)
if r >= 0 and r < 7 and c >= 0 and c < 7 and (r != row or c != column)
if grid[r, c] == 1
around = around + 1
if current == 1
if around == 2 or around == 3
1
else
0
else
if around == 3
1
else
0
word advance(grid: Array<Int>) -> Array<Int>
let following: Array<Int> = array.new([7, 7], 0)
for row in range(0, 7)
for column in range(0, 7)
following[row, column] = next-cell(grid, row, column)
following
word show(grid: Array<Int>, generation: Int) -> Array<Int>
print("Generation " + int.to-string(generation))
for row in range(0, 7)
var line = ""
for column in range(0, 7)
if grid[row, column] == 1
line = line + "#"
else
line = line + "."
print line
grid
word seed(grid: Array<Int>, cells: List<List<Int>>) -> Array<Int>
for cell in cells
grid[cell[0], cell[1]] = 1
grid
word generations(grid: Array<Int>, count: Int) -> Array<Int>
var current = grid
for generation in range(1, count + 1)
current = advance(current)
show(current, generation)
current
flow array.new([7, 7], 0)
seed([[2, 3], [3, 4], [4, 2], [4, 3], [4, 4]])
show 0
generations 4
Run
zhex run examples/life.zhexOutput
Generation 0 ....... ....... ...#... ....#.. ..###.. ....... ....... Generation 1 ....... ....... ....... ..#.#.. ...##.. ...#... ....... Generation 2 ....... ....... ....... ....#.. ..#.#.. ...##.. ....... Generation 3 ....... ....... ....... ...#... ....##. ...##.. ....... Generation 4 ....... ....... ....... ....#.. .....#. ...###. .......
Edit distance
Fill a dynamic-programming table to compare Unicode text.
# Levenshtein distance counts insertions, deletions, and substitutions.
word min(left: Int, right: Int) -> Int
if left < right
left
else
right
word distance(left: String, right: String) -> Int
let rows = text.length left
let columns = text.length right
let costs: Array<Int> = array.new([rows + 1, columns + 1], 0)
for row in range(0, rows + 1)
costs[row, 0] = row
for column in range(0, columns + 1)
costs[0, column] = column
for row in range(1, rows + 1)
for column in range(1, columns + 1)
let deletion = costs[row - 1, column] + 1
let insertion = costs[row, column - 1] + 1
var change = 0
if text.slice(left, row - 1, row) != text.slice(right, column - 1, column)
change = 1
let substitution = costs[row - 1, column - 1] + change
costs[row, column] = min(min(deletion, insertion), substitution)
costs[rows, columns]
print("kitten → sitting: " + int.to-string(distance("kitten", "sitting")))
print("empty → abc: " + int.to-string(distance("", "abc")))
print("café → cafe: " + int.to-string(distance("café", "cafe")))
Run
zhex run examples/edit-distance.zhexOutput
kitten → sitting: 3 empty → abc: 3 café → cafe: 1
Collatz steps
Count the steps each number takes to reach 1 with a while loop.
# Collatz step counts: a while loop terminates by its condition, not a bound.
word collatz-steps(start: Int) -> Int
var n = start
var count = 0
while n != 1
if n % 2 == 0
n = n / 2
else
n = 3 * n + 1
count = count + 1
count
for start in range(1, 10)
print(int.to-string(start) + ": " + int.to-string(collatz-steps(start)))
Run
zhex run examples/collatz.zhexOutput
1: 0 2: 1 3: 7 4: 2 5: 5 6: 8 7: 16 8: 3 9: 19
Language details
A few words worth knowing.
letcreates an immutable binding.varallows rebinding.flowpasses each result to the next operation.tryunwraps success or propagates a compatible failure.- Palindrome checking preserves case, spaces, and punctuation.