Cookbook
Practical Stage-0 recipes for CSV text, grouping, maps, mutable collections, sorting, and pipelines.
These recipes are current Stage-0 patterns from .sources/vela/docs/COOKBOOK.md and runnable examples in
.sources/vela/examples. They avoid planned syntax unless called out explicitly.
1. Parse a simple CSV string
For plain comma-separated data without quoting or escaping, split the text into lines, split each row, and zip headers to fields with record updates.
# Source: .sources/vela/examples/text_csv.vela
fn lines(text):
return split(text, "\n")
fn trim(s):
cs = chars(s)
mut lo = 0
mut hi = cs.len
while lo < hi and cs[lo] == " ":
lo = lo + 1
while hi > lo and cs[hi - 1] == " ":
hi = hi - 1
return substr(s, lo, hi - lo)
fn parse_row(line):
mut out = []
for f in split(line, ","):
out = push(out, trim(f))
return out
fn row_to_record(header, row):
mut rec = {}
mut i = 0
while i < header.len and i < row.len:
rec = set(rec, header[i], row[i])
i = i + 1
return rec
fn parse_csv(text):
ls = lines(text)
header = parse_row(ls[0])
mut records = []
mut i = 1
while i < ls.len:
records = push(records, row_to_record(header, parse_row(ls[i])))
i = i + 1
return records
2. Group and aggregate rows
Use a mutable dict() when you want in-place accumulation. Use records plus set / get_or when you want
immutable map-style updates.
# Source: .sources/vela/examples/codex_data_groupby.vela
rows = csv_rows(csv)
cities = ["NYC", "LA", "SF"]
sums = dict()
counts = dict()
for city in cities:
dict_set(sums, city, 0.0)
dict_set(counts, city, 0)
for row in rows:
city = row[1]
salary = float(row[2])
dict_set(sums, city, dict_get(sums, city) + salary)
dict_set(counts, city, dict_get(counts, city) + 1)
3. Sort by a key
Stage-0 has builtin sort for all-number or all-string lists. For records, the cookbook defines a small
insertion-sort helper that accepts a key lambda.
fn sort_by(xs, key):
mut out = []
for x in xs:
mut placed = false
mut next = []
for y in out:
if not placed and key(x) < key(y):
next = push(next, x)
placed = true
next = push(next, y)
if not placed:
next = push(next, x)
out = next
return out
people = [{ name: "Ada", age: 36 }, { name: "Lin", age: 28 }]
sorted_people = sort_by(people, p => p.age)
4. Pipeline map/filter/reduce
Pipelines thread the value on the left into the first argument on the right.
result = [1, 2, 3, 4, 5, 6] |> filter(n => n % 2 == 0) |> map(n => n * n) |> reduce(0, (a, b) => a + b)
print(result)
5. Choose immutable or mutable collections
- Immutable list append:
ys = push(xs, value). - Mutable array append:
array_push(a, value). - Immutable record-map update:
m = set(m, key, value). - Mutable dictionary update:
dict_set(d, key, value).