The Rowan Handbook

Language, runner and debugger · Version 1.3.1

Start on Windows

Rowan lets you describe a result and hand the bookkeeping to the interpreter. A query can turn a CSV of cube solves into personal bests. A solve expression can place four queens on a board by trying only choices that still satisfy your rules. Use ordinary functions and loops for the parts of a program that need a sequence of actions.

Open hello.rowan for a two-line greeting, tour.rowan for a one-page tour of everyday text and list work, or practice/desk.rowan for an app that remembers its data. If you are new to programming, read Rowan at a glance next, then Build an interactive app.

Rowan and Bowen share one interpreter. Rowan files (.rowan) use braces { } for blocks. Bowen files (.bow) use indentation. Everything in the standard library works the same in both. The Bowen Handbook covers the indented style.

Edit and debug in Rowan Studio

Double-click Open Rowan Studio.cmd and keep its terminal open. Studio opens in your default browser. The editor, project files and interpreter run on your PC. If the tab does not open automatically, paste the address printed by the launcher into your browser.

  1. Open robot_lab.rowan in the project sidebar. Click Run. With a budget of 65 the winning combination is Scout and Plus, for 8 hours at a cost of 56.
  2. Change let budget = 65 to let budget = 70 and run again. Studio saves the edit and starts a fresh interpreter. The winning combination changes to Scout and Max, 12 hours at a cost of 70.
  3. Click line 18, the maximize clause, to set a breakpoint. Click Debug, then Continue. Studio highlights the objective before evaluating it. Enter pack.capacity / motor.draw under Inspect expression and click Inspect. The first feasible pair, Scout and Light, scores 4.0.
  4. Click a frame to see its variables. Over executes the next step at the current call depth. Into follows calls. Out returns to the caller. Click line 18 again to clear the breakpoint, then Continue to finish. Stop ends the separate worker process, including a program waiting for input or stuck in a loop.

Use + New to create my_program.rowan. A name such as tools/helpers.rowan also creates the project subfolder. Save writes to disk. Starting a run or switching files saves pending edits. Use the ••• menu to save a copy or reload a file after editing it elsewhere. If the copy on disk has changed since you opened it, Studio asks you to resolve the conflict. You can edit Rowan, CSV, JSON and text files in the sidebar.

Check parses the current program and its imports. Click the filename beside a diagnostic to jump to its source. Debugging an uncaught runtime error preserves the stack and variables for inspection. Choose Finish when you are done. The Output panel streams printed lines, provides a text box for input(), and accepts EOF for end of input. Put command-line arguments in the sidebar. Double quotes keep a phrase together.

ShortcutAction
Ctrl+SSave the current file.
Ctrl+EnterSave and run the current program.
F5Start debugging, or continue a paused program.
F9Toggle a breakpoint on the cursor’s line.
F10 / F11 / Shift+F11Step over / into / out.

On the first launch Studio copies the examples to a writable projects folder. Your changes stay there, and the original examples remain available under examples. To open your own existing folder, run .\rowan.cmd studio "D:\Code\My Project". The editor works offline once the Python runtime is available. Ctrl+C in the launcher terminal closes the local server.

Upgrading from an earlier release. Extract 1.3 into its own folder. Open the folder containing your existing .rowan files with the command above. If you installed the private runtime, you can copy its runtime folder beside the 1.3 launcher and use it again. Existing programs keep working. Release 1.3.1 only adds features.

Use the terminal menu

  1. Extract the entire ZIP to a writable folder, such as Documents. Open Bowen-1.3 and double-click Start Rowan.cmd.
  2. Choose 1. The runner reads examples\solves.csv and prints one row per puzzle, including its best and average official times.
  3. Choose 2 and enter the expression below. The answer is 30. Change 10 to 20 and try to predict the new answer. Use .quit to leave the prompt.
  4. Choose 5. Notepad opens my_program.rowan. Replace the greeting with print("Hello, Rowan!"), save and close the editor, then choose 6. Your file remains in the extracted folder between runs.
  5. Choose 4 to reopen this handbook. 7 and 8 accept a path to any Rowan program, including a file dragged from Explorer.
1..10 |> where it % 2 == 0 |> sum it

If the launcher offers a private Python runtime, choose Y. You can also open Setup Runtime.cmd directly. It downloads the official Python 3.14.9 embeddable runtime for x64 or ARM64 Windows, checks the SHA-256 digest, and tests Rowan before installing the runtime inside the extracted folder. This one-time step needs internet. An existing Python 3.10 or newer also runs Rowan. The interpreter and standard library work offline. Python release files and checksums

Run from a terminal

In Explorer, open the extracted Bowen-1.3 folder and choose Open in Terminal. These commands use PowerShell. Paths containing spaces need double quotes.

.\rowan.cmd --version
.\rowan.cmd repl
.\rowan.cmd run examples\cube_report.rowan
.\rowan.cmd check examples\club\main.rowan
.\rowan.cmd debug examples\debug_me.rowan
.\rowan.cmd run examples\notebook.rowan add "Try a new chess opening"
.\rowan.cmd run examples\notebook.rowan list
.\rowan.cmd test

run executes a file. check parses the file and all statically referenced imports, even imports inside functions or untaken branches. Name resolution, record checks and operations on values happen at run time. debug executes under the source debugger. test with no path runs the bundled release tests. test file-or-folder runs your Rowan test blocks. Success returns exit code 0, a program or check error returns 1, and an invalid command line returns 2. args() returns the strings following the program filename. An optional initial -- separates them from the filename.

On another system with Python 3.10+, substitute python3 rowan.py for .\rowan.cmd. You can use the same form with py -3 rowan.py on Windows if that launcher is installed.

Use the interactive prompt

Bindings survive until you exit the session. Enter an expression to see its value. Opening a brace, bracket or parenthesis lets you continue typing on the next line. To paste a complete program or a pipeline across several lines, enter .edit on its own line, paste the code, then enter .end. Use .cancel to discard pending input, .help for commands, and .quit to leave. Program files print only when you call print.

Type print(help()) to list every built-in function and module, or print(help(str)) to list the functions inside one module.

Rowan at a glance

This chapter fits the whole everyday language on one page. Each later chapter explains a topic in depth. Run examples\tour.rowan to see most of these lines working together.

The ten things you will use most

let name = "Aya"                       # create a binding
set name = "Mira"                      # change it later
let scores = [72, 95, 64]              # a list
let player = {name: "Aya", best: 95}   # a map with named fields
set player.best += 2                   # update a field in place

if player.best >= 90 {
    print("Excellent,", player.name)
} else {
    print("Keep going")
}

for score in scores { print(score) }
for key, value in pairs(player) { print(key, value) }

fn double(n) => n * 2                  # a one-line function
fn grade(score) {                      # a block function
    if score >= 70 { return "pass" }
    return "retry"
}
print(map(scores, grade))              # ["pass", "pass", "retry"]

Cheat sheet

I want to…Write
Show somethingprint("Total:", total) or say "Hello, {name}!"
Ask the userask age: int "How old are you?" between 1 and 120
Make a decision in one linelet label = when n > 0 then "positive" else "not positive"
Count from 1 to 10for n in 1..10 { ... }
Count in stepsfor n in range(0, 100, 10) { ... } (includes 100)
Add to a numberset total += n (also -=, *=, /=, %=)
Get part of a list or textitems[1:3], items[:2], name[-3:]
Keep matching itemsfilter(scores, fn(s) => s >= 70) or scores |> where it >= 70
Transform every itemmap(scores, fn(s) => s + 5) or scores |> select it + 5
Sortsorted(scores), sorted(names, len), sorted(scores, none, true) for descending
Total, smallest, largestmath.sum(scores), math.min(scores), math.max(scores)
Find the first matchfind(people, fn(p) => p.age > 18) returns none if nothing matches
Format moneystr.fixed(1234.5) gives "1,234.50"
Line up columnsstr.padRight(item, 10), str.padLeft(text(n), 6)
Pick at randomrandom.int(1, 6), random.pick(colors), random.shuffle(cards)
Read and write filesfs.read("notes.txt"), json.write("data.json", value), csv.read("data.csv")
Handle a problemtry { ... } catch problem { print(problem.message) }
Check your workassert total == 50, "The total should be 50."

Reading an error message

When something goes wrong, Rowan prints the file, line and column, shows the line, and points at the problem with ^. The message is written to tell you what to do next.

examples\shop.rowan:4:7: Unknown name 'totl'. Did you mean 'total'?
  print(totl)
        ^
Message starts withIt usually means
Unknown name 'x'. Did you mean 'y'?A spelling mistake, or the binding was never created with let.
No field named 'x'The map or record has no such field. The suggestion lists the closest real field.
Cannot use + with text and intYou mixed text and numbers. Use text(n) to turn a number into text, or toNumber(s) to read a number from text.
'count' is a reserved wordWords such as count, sum, first, select and where belong to the language. Pick a different name.
Expected '}', found the end of the fileA block was opened with { but never closed. Count your braces.
Too many nested callsA function calls itself and never reaches a stopping case. Rowan allows thousands of nested calls, so a correct recursive function will not hit this limit.
File not foundThe path is relative to the program's folder. Print fs.base() to see that folder.

Build an interactive app

Ask a question and greet someone

Open hello.rowan in Rowan Studio and click Run. Enter your name in the Output panel and press Enter.

ask name "What's your name?"
say "Hello, {name}!"

The first line declares name, trims the answer and asks again if it is blank. The second inserts the answer into the greeting. In say, ask and menu strings, {name} looks up a binding and {row.name} looks up a field. Use {{ and }} for literal braces. Elsewhere, use an explicit template like let message = $"Hello, {name}!". Ordinary strings keep their braces. To show a calculated value, give the expression a name and insert that name.

Validate a whole form

let session = form {
    ask activity "What did you practice?" from ["Chess", "Coding", "Violin"]
    ask minutes: int "How many minutes of {activity}?" between 1 and 240
    ask official: bool "Count toward the goal?" default true
}
say "Logged {session.minutes} minutes of {session.activity}."

Try Chess, then three, then 15. Only the minutes question repeats. Each field can use earlier answers. Completing the form produces a map. Field names stay inside it. In Studio a choice question displays a dropdown. In the terminal you can type a choice in any letter case. Both return the spelling in the original list.

DeclarationWhat Rowan does
ask name "Name?"Creates a text binding in the current scope. Trims surrounding whitespace and requires a nonempty answer.
ask n: int "Minutes?" between 1 and 240Retries until it gets a whole number within the inclusive bounds. The bounds may use variables.
ask t: number "Seconds?"Accepts a finite integer or decimal.
ask mode "Mode?" from ["Rapid","Blitz"] default "Rapid"Offers allowed values. Pressing Enter selects the default.
ask ready: bool "Ready?"Accepts yes/no, y/n or true/false. The result is a boolean.

A question may use from or between followed by an optional default. Choices and defaults must match the declared type. Invalid question definitions fail immediately. A form requires at least one ask and unique field names. End of input raises a catchable error with code == "input_end". A half-completed form never returns a partial record.

Build a menu

fn greet() {
    ask name "Name?"
    say "Hello, {name}!"
}
menu "What would you like to do?" {
    "Greet me" => greet()
    "Show the date" => print(date.today())
}

The menu handles showing choices, reading the selection, running the chosen expression and returning to the menu. Rowan supplies Quit. End of input at the menu or inside one of its actions exits that menu. Labels must be unique after trimming and ignoring case. Put a longer action in a function. Clicking the line number beside a label sets a debugger breakpoint on that action.

Keep records after closing the app

record Session(activity: text, minutes: int)
collection journal: Session in "practice.sqlite"

let id = journal.add({activity: "Chess", minutes: 15})
let saved = journal.change(id, {minutes: 20})
say "Session {saved.id} now has {saved.minutes} minutes."

This creates or opens a local SQLite database in the entry program’s data directory. The collection validates field names and types and assigns numeric IDs. Each call commits before it returns. On a later run, the same collection name and field types open the existing data. One database can contain several named collections. Several running programs can use the same database.

OperationResult
journal.add(row)Validate a plain map or typed record, store it and return its new ID.
journal.addAll(rows)Insert a batch in one transaction. A failed row rolls back the whole batch. Returns IDs in input order.
journal.all()Return plain maps containing id and the stored fields, in insertion order.
journal.find(id)Return the row, or none when the ID is missing.
journal.change(id, changes)Validate and commit a partial update. Return the updated row. Missing IDs raise an error.
journal.remove(id)Delete one row and return whether a row was removed.
journal.count()Count rows without loading them.

Rows store JSON-compatible data. Nested records round-trip as maps. The field id belongs to the collection. IDs can have gaps. Changing a collection’s declared field names or types requires a new collection or explicit data migration. Reordering declarations is fine. Keep the database alongside the program if you move your existing project.

Summarize and publish results

let solves = [
    {puzzle: "2x2", seconds: 13},
    {puzzle: "3x3", seconds: 58},
    {puzzle: "2x2", seconds: 22}
]
let board = solves |> summarize by it.puzzle {
    attempts: count, best: min it.seconds, average: average it.seconds
}
print(table(board))
let output = report.write("cube-report.html", "Best cube solves", board, "key", "best")
say "Open {output} to see the chart."

The 2×2 row has two attempts, a best of 13 seconds and an average of 17.5. summarize by produces a row per group, in first-seen order. Each row contains key plus the metric fields you declare. Available reducers are count, sum, average, min and max. They use the same rules as their corresponding pipeline stages. Empty input produces an empty list.

report.write(path, title, rows) writes a self-contained HTML table and returns its path. Add a label field and a nonnegative numeric field for a bar chart. Open that file in a browser or send someone the HTML. It works offline. Text and field names are escaped.

Pick a branch by its data

fn classify(entry, goal = 20) {
    return match(entry) {
        case {minutes: n} if n >= goal => "goal reached"
        case {minutes: n} if n > 0 => "in progress"
        else => "no practice"
    }
}
print(classify({minutes: 15}, goal: 10))

This prints goal reached. Rowan evaluates the subject once, tests arms from top to bottom and runs the first matching arm whose optional guard is true. Captures such as n belong only to that arm. else => is required. A map pattern requires the named fields and allows extras. A list pattern matches the exact length. Patterns can nest. A literal checks equality, a bare name captures the value and _ ignores it. Separate arms with newlines or semicolons. For ordinary true/false decisions, if and else still work.

Functions, statistics and dates

Optional function parameters use =. Supplied arguments evaluate in written order. When omitted, each default evaluates at call time and can use earlier parameters or captured bindings. Put required parameters first. Use name: value at a call site to supply named arguments in any order. Positional arguments come first. Record constructors also accept field names in any order. Standard library functions use positional arguments.

CallResult
stats.summary([13, 22, 19])A map with count, min, max, mean and median. Empty input gives a count of zero and none for the other fields.
date.today()The PC’s local date as ISO text, for example "2026-11-21".
date.addDays("2024-02-28", 1)"2024-02-29", including leap-day handling.
date.daysBetween("2024-02-29", "2024-03-02")2, measured from the first day to the second.
date.weekday("2024-02-29")"Thursday". Date inputs use YYYY-MM-DD.

Test and share your own program

Open practice/practice.test.rowan and click Test. All three named tests should pass. Change one expected value in your project copy and click Test again to see the failing assertion and its line number. The following is an independent test file:

fn double(n) => n * 2

test "doubling zero" {
    assert double(0) == 0
}
test "doubling a negative number" {
    assert double(-4) == -8
}

Run skips test bodies. Test runs each top-level named test with fresh in-memory bindings and a fresh module cache. It executes the file’s top-level setup before each case. Put reusable functions in modules and assertions in a separate *.test.rowan file. Filesystem changes are real and persist between cases. A failure reports its location, and the remaining cases still run.

.\rowan.cmd test examples\practice
.\rowan.cmd pack examples\practice\desk.rowan -o Practice-App.zip

A folder test discovers *.test.rowan recursively. You can also test one specific file. With no path, test runs the toolchain’s own release suite.

Pack creates a Windows-ready ZIP containing the entry file, local imports, interpreter source, runtime setup and a Run App.cmd launcher. Extract the ZIP in a writable folder and open the launcher. A compatible Python installation or the optional one-time runtime download is required. Subsequent runs can work offline. The entry file’s relative path and import structure are preserved.

Pack includes static use dependencies. Include data files explicitly with --asset, once per file. Asset names are relative to the project root. By default that root is the entry file’s directory. Set --root to a common ancestor if the entry uses modules in a sibling directory. Use a fresh output name. A database your program has already populated is included only when you explicitly name it as an asset.

.\rowan.cmd pack examples\cube_report.rowan --asset solves.csv -o Cube-Report.zip

Write a query

From CSV to a leaderboard

The sample CSV has three columns named puzzle, seconds and official. Its 3x3,48,false row is an unofficial trial. The following is the entire reporting program apart from its comment. You can edit the CSV and rerun it.

record Solve(puzzle: text, seconds: number, official: bool)
let solves = csv.read("solves.csv", Solve)
let report = solves
    |> where it.official
    |> group by it.puzzle
    |> select {
        puzzle: it.key,
        solves: it.items |> count,
        best: it.items |> min it.seconds,
        average: math.round(it.items |> average it.seconds, 2)
    }
    |> sort by it.best
print(table(report))
puzzle    solves  best  average
--------  ------  ----  -------
Pyraminx  2       10.6  13.2
2x2       2       13    17.5
3x3       2       58.4  61.7

A Python program using only its standard library would usually arrange the CSV conversion, grouping dictionary and per-group reductions itself. Here the record declaration tells the CSV reader how to convert each cell. group by builds the groups. In the outer select, it is one group with fields key and items. Inside min it.seconds or average it.seconds, it is one solve from that group. Each stage hands its result to the next |>.

Try it. Change the unofficial 3×3 result to true and rerun. Its best becomes 48 and its average becomes 57.13. To inspect the official solves before grouping, start the debugger, enter b 6, then c and p rows.

Pipeline reference

Stages consume lists. Predicates produce booleans. A projection is an expression evaluated once per row with it bound to that row. take and skip evaluate their argument once in the surrounding scope. Use parentheses to feed a whole pipeline into another expression.

StageResult
where predicateList of rows for which the predicate is true.
select expressionList of projected values. Each value can be a map, list, scalar, or other Rowan value.
sort by expression [asc/desc]Rows in stable key order. The default is ascending. Keys must be all numeric or all text.
group by expressionList of {key, items} maps, ordered by the first appearance of each key. Items retain input order.
distinct by expressionFirst row for each distinct key, in input order.
join right on leftKey equals rightKeyInner equality join. Each match yields {left, right}. Each key expression sees its own side as it. Duplicate matches produce all pairs in left-then-right input order.
take n, skip nUp to the first n rows, or the remaining rows. n is a nonnegative integer.
count, firstNumber of rows, or the first row. first of an empty list is none.
sum expression, average expressionNumeric total or mean. An empty total is 0. An empty mean is none.
min expression, max expressionSmallest or largest projected number or text. Empty input gives none.
some predicate, every predicateTest existence or universal agreement and stop once the answer is known. On empty input they return false and true respectively.

Group and join keys can also be lists or maps. For a two-column key use [it.club, it.season]. Query stages work in memory. A later take 1 receives the list produced by the preceding stage.

Combine two data sets

let people = [{id: 7, name: "Mira"}, {id: 9, name: "Sol"}]
let scores = [{id: 9, points: 4}, {id: 7, points: 3}]
let names = scores
    |> join people on it.id equals it.id
    |> select {name: it.right.name, points: it.left.points}
print(table(names))

The output lists Sol with 4 points and Mira with 3. The examples\club project uses a module to turn this join into a reusable standings function.

Describe a search

solve explores finite choices in the order you give them. require checks a partially built choice immediately. If it fails, Rowan skips every later choice that depends on that prefix. yield produces the result for one surviving combination. You supply the choices, rules and result shape. The interpreter handles nesting, pruning and backtracking.

let pairs = solve {
    choose a from 1..6
    choose b from a..6
    require a + b == 7
    yield [a, b]
}
print(pairs)

This prints [[1, 6], [2, 5], [3, 4]]. Starting b at a gives each unordered pair once. A later domain can depend on earlier choices. Choice names are local to the search.

let plan = solve first {
    choose sensor from [{name: "basic", cost: 18}, {name: "pro", cost: 42}]
    choose battery from [{hours: 2, cost: 12}, {hours: 5, cost: 25}]
    require sensor.cost + battery.cost <= 50
    require battery.hours >= 4
    yield {sensor: sensor.name, hours: battery.hours}
}
print(plan)

The result is {"sensor": "basic", "hours": 5}. solve first stops at the first valid combination and returns none if no combination works. Plain solve returns all results in a list, including an empty list when nothing matches. A domain must be a list, a requirement must be boolean, and the final clause must be yield. Put a cheap, restrictive requirement immediately after the choice it can check. Functions called inside a search run once for each explored prefix that reaches them.

Try the chess example. Run examples\four_queens.rowan. It finds both legal arrangements of four queens and prints the boards. Set a breakpoint on its last require to inspect a candidate column before Rowan accepts or rejects it.

Optimize with several goals

solve best picks the highest-ranked feasible result. List the most important objective first. A later objective decides ties in earlier ones.

let projects = [
    {name: "Radar", points: 8, hours: 5},
    {name: "Arm",   points: 9, hours: 7},
    {name: "Rover", points: 9, hours: 6}
]
let pick = solve best {
    choose project from projects
    require project.hours <= 7
    maximize project.points
    minimize project.hours
    yield project.name
}
print(pick)

Rowan prints Rover. It ties Arm on points and takes one hour less. Each minimize or maximize must produce a number. Put objectives after all choose and require clauses and before yield. At least one objective is required. Equal ranks keep the first candidate in choice order. With no feasible candidate the result is none. The yield expression runs once, for the winner. Objectives run for every feasible candidate, so use side-effect-free scoring expressions for predictable results.

The current implementation enumerates feasible candidates and retains the best choice seen so far. Earlier require clauses prune the search, and you can debug individual objectives. The optimization needs no sorted list of all candidate results. Use solve first when you just need the first feasible choice.

Core language

Values and expressions

Text uses UTF-8 and double quotes. Strings accept JSON escapes including \n, \t, \", \\ and \uXXXX. Comments start with # outside a string. Names are case-sensitive ASCII letters, digits and underscores, starting with a letter or underscore. A newline or semicolon separates statements. You can split expressions inside parentheses, lists, record literals, after a binary operator, or before a pipeline marker. Indentation helps readers. Braces determine block boundaries.

ValueExamples and behavior
Absence and booleansnone, true, false. Conditions, and, or and not require booleans.
Numbers42, -3, 0.25, 1e3. Integer arithmetic preserves integer precision. Division produces a finite floating-point value. typeOf(1) is "int" and typeOf(1.0) is "number".
Text"knight". Indexing works by Unicode code point. Use + to concatenate two texts.
Lists[3, 5, 8]. xs[0] picks the first item, xs[-1] the last. xs[1:3] slices items 1 and 2, xs[:2] the first two and xs[-2:] the last two. Slices work on text too. + joins two lists.
Maps{name: "Aya", "best time": 13}. Keys are text. m.name and m["name"] are equivalent. Iteration visits keys in insertion order.
Typed recordsrecord Point(x: number, y: number) declares a constructor. Point(3, 4) validates each value. typeOf returns the declared name.
Functions and modulesFunctions are values that can be returned, stored or passed as arguments. Modules expose their exported bindings through fields.

Lists and maps compare by content. Map key order does not affect equality. Typed records compare by constructor identity and field values. An integer and an equal decimal compare equal. Booleans are distinct from numbers. Functions, schemas and modules compare by identity.

Operators, strongest to weakest

OrderOperators
1Calls f(x), lookup x[i], field x.name
2Unary not, +, -
3*, /, % (remainder has the sign of the divisor)
4+, -
5Inclusive integer range a..b, ascending or descending
6<, <=, >, >=, in
7==, !=
8–10and, then or, then ??
11Pipeline |>

Binary operators at the same level associate left to right. Write a < x and x < b for a bounded comparison. a ?? b evaluates b only if a is none. and and or short-circuit. in tests list membership, a map key or a text substring. when condition then yes else no computes one branch only. Parenthesize a branch that ends in its own pipeline.

Bindings and updates

let player = {name: "Mira", scores: [8, 10]}
let earlier = player
set player.scores[0] = 9
set player.team = "North"
assert earlier.scores[0] == 8
assert player.scores == [9, 10]

let creates a binding in the current scope. set updates the nearest existing binding. set total += 5 is shorthand for set total = total + 5. The same works for -=, *=, /= and %=, and for fields and indexes such as set player.scores[1] += 1. A block can shadow an outer name. A second declaration in the same scope is an error. Lists and records have value semantics. A nested update copies the containers along that path, so an earlier value remains available through another binding. A plain map accepts new fields. A typed record keeps its original fields and validates field updates.

Record fields may declare any, text, number, int, bool, list or map. An omitted annotation means any. The map annotation accepts typed records as well. A record constructor accepts positional arguments in declaration order or named fields. Ordinary function parameters accept any value.

Branches, loops and calls

fn factorial(n) {
    assert n >= 0, "Expected a nonnegative integer."
    if n <= 1 { return 1 }
    return n * factorial(n - 1)
}
fn twice(n) => n * 2

let total = 0
for n in 1..5 {
    if n == 3 { continue }
    set total = total + n
}
while total > 10 { set total = total - 1 }
print(factorial(5), twice(total))

This prints 120 20. if accepts optional else if and else branches. for visits list items, text characters or map keys. for key, value in pairs(m) unpacks each item into several names. The items must be lists of the same length, as pairs, zip and indexed produce. Each iteration gets a fresh scope. while reevaluates its condition before each iteration. break exits the nearest loop and continue advances to its next iteration. The range 3..1 produces [3, 2, 1]. Use [] when you need an empty sequence.

Functions capture bindings from the scope where they are defined. Named functions can call themselves, up to 10,000 calls deep on Python 3.11 or newer. Calls evaluate their arguments from left to right and fill any omitted optional parameters using their defaults. An explicit return exits a function. A bare return or reaching its closing brace returns none. A => body returns its expression.

fn counter(start) {
    let n = start
    return fn() { set n = n + 1; return n }
}
let tick = counter(40)
print(tick(), tick())
let product = fold([2, 3, 4], 1, fn(acc, value) => acc * value)
assert product == 24

Modules

Save related definitions in another .rowan file. This could be tools.rowan:

export record Reading(label: text, value: number)
export fn doubled(reading) => reading.value * 2

In a neighboring main.rowan:

use "tools.rowan" as tools
let sample = tools.Reading("signal", 7)
print(tools.doubled(sample))

The output is 14. An import path is relative to the file containing use. Rowan executes a module the first time it is imported in a run and caches it by resolved path. Each module has a private top-level scope. export exposes a top-level let, fn or record. Exported bindings reflect updates made inside the module. An import cycle raises an error. The standard library modules are already in scope.

Errors and assertions

fn divide(a, b) {
    if b == 0 { throw "The divisor is zero." }
    return a / b
}
try {
    print(divide(12, 0))
} catch problem {
    print(problem.message, "on line", problem.line)
}
assert divide(12, 4) == 3, "Division check failed."

A runtime error unwinds calls until a matching catch. The error map contains message, file, line and column. throw accepts a value and uses its text representation as the message. An assertion checks a boolean and evaluates its optional custom message on failure. Uncaught errors show the source location and call chain. The runner parses each file before running the statements in it.

Use the debugger

Fix the sample bug

Run .\rowan.cmd debug examples\debug_me.rowan or choose 3 in the launcher. The program is supposed to add 1 through 4. The debugger pauses before the first statement. Enter these commands one at a time:

CommandWhat you learn
b 5 if n == 4Sets a conditional breakpoint at the line that decides whether to break.
cRuns until the loop reaches its last number.
p [n, total, limit]Prints [4, 6, 4]. Four is still missing from the total.
btShows totalThrough and the line in the main program that called it.
oRuns until the function returns and pauses before the next main-program statement.
p answerPrints 6. The loop broke before it could add its last value.
c, then qContinues to the failed assertion and exits the postmortem prompt.

Copy the sample to my_sum.rowan. In the copy, delete if n == limit { break }. Save and run it. The output becomes Sum through 4 = 10 and the assertion passes. Keeping the original example makes the bundled release test repeatable.

Command reference

CommandAction
step (s)Move to the next statement, search clause or multiline query stage, entering function calls.
next (n)Advance at the current call depth or shallower.
out (o)Run until control reaches a shallower call frame.
continue (c)Run to a breakpoint, an uncaught error or the end.
break (b)List breakpoints. Add line or file:line to set one. Append if expression for a conditional breakpoint.
clear line, clear file:line, clear allRemove breakpoints.
print expression (p)Evaluate Rowan in the selected frame. A call can perform I/O or update captured bindings, just as it can in a program.
localsShow visible program bindings, including names captured by closures.
stack (bt), up, downSee the call stack and select a caller or callee for inspection. Stepping always controls the live execution point.
list (l)Show source lines around the selected frame.
help (h), quit (q)Show commands or end the session.

Breakpoints fire before executable code. Use a statement, a solve clause or a pipeline stage on its own line. A comment, blank line or closing brace has no execution event. File-qualified breakpoints resolve relative to the selected source file. You can set one in an imported module before that module is loaded.

When you pause on a multiline |> stage, rows is the incoming list for that stage. Try p rows |> count or p rows |> take 2. After an uncaught runtime error you can inspect the saved call frames, then type q to leave. The program retains its failure exit status.

Standard library

All signatures below use square brackets for optional arguments. The brackets in a signature are documentation notation. fs, csv and json resolve relative data paths against the entry program’s folder. In the interactive prompt the base is the directory where you started Rowan. Imports use the importing module’s folder.

Console and values

FunctionContract
print(values...)Write a space-separated line. Returns none.
input([prompt])Read one line of text. End of input returns none.
args()List of command-line arguments after the filename.
typeOf(x)Type name, including the name of a typed record.
text(x)Human-readable representation of a value.
toInt(x)Convert decimal integer text or a whole numeric value to an integer.
toNumber(x)Convert numeric text or return a numeric value.
len(x)Number of characters, list items or fields.
keys(m), values(m)Field names or values in insertion order.
get(x, key[, fallback])Look up an item in a text, list or map. A missing field or index returns the fallback, whose default is none.
put(x, key, value)Return a list, map or typed record with one position updated.
push(list, value)Return a list with the value appended.
slice(x, start[, end])Slice text or a list. Start is inclusive and end is exclusive. End defaults to the length. Indices may be negative and bounds are clipped.
fold(items, initial, fn)Repeatedly call fn(accumulator, item), returning the final accumulator.
table(rows)Render a list of maps or records as a text table. Columns follow first occurrence.
help([module])With no argument, list every built-in function and module. With a module such as str, list its functions. Wrap it in print.

Lists

These functions take a list and return a new one. The original list never changes. Functions such as map take another function as an argument, either a named one like grade or an inline fn(x) => .... Pipeline stages such as where and select do the same jobs with it and are often shorter. Use whichever reads better.

FunctionContract
range(start, end[, step])Integers from start to end, including end, like start..end. range(0, 10, 5) is [0, 5, 10]. Without a step it counts up or down. A step pointing away from end gives [].
sorted(items[, key[, descending]])A sorted copy. key is a function applied to each item, or none to sort by the items themselves. Pass true third for largest first: sorted(scores, none, true). Equal keys keep their original order.
map(items, fn)A list of fn(item) for each item.
filter(items, fn)The items for which fn(item) is true.
find(items, fn)The first item for which fn(item) is true, or none.
indexOf(items, value)Position of the first equal item, or -1. Also finds text inside text.
unique(items)Items with duplicates removed, keeping first appearances.
reverse(x)A list or text in reverse order.
flatten(items)Joins nested lists one level deep: [[1], [2, 3]] becomes [1, 2, 3].
zip(a, b), indexed(xs), pairs(m)Pair items up, number them from 0, or turn a map into [key, value] lists.
windows(items, width)Every run of width neighboring items.

Text and arithmetic

FunctionContract
str.lower(s), str.upper(s)Change letter case.
str.trim(s)Remove leading and trailing whitespace.
str.split(s, sep)Split at a nonempty literal separator.
str.join(strings, sep)Join text items with a separator.
str.replace(s, old, new)Replace all literal occurrences.
str.starts(s, prefix), str.ends(s, suffix)Test a prefix or suffix.
str.lines(s)Split text at line breaks.
str.contains(s, part), str.find(s, part)Test whether part appears, or return its first position (-1 if missing).
str.count(s, part)Count non-overlapping occurrences.
str.repeat(s, n), str.chars(s)Repeat text n times, or split it into single characters.
str.padLeft(s, width[, fill]), str.padRight(...)Pad to at least width characters. str.padLeft("7", 3, "0") is "007". Great for lining up columns.
str.title(s)Capitalize the first letter of each word.
str.isNumber(s)true when toNumber(s) would succeed. Use it to check input before converting.
str.fixed(x[, digits])A number as text with exactly digits decimal places (default 2) and thousands separators: str.fixed(1234.5) is "1,234.50".
math.abs(x), math.sqrt(x)Absolute value or real square root.
math.floor(x), math.ceil(x)Round down or up to an integer.
math.round(x[, digits])Round to decimal places, default zero. Exact halfway ties go to the even result. Decimal inputs use binary floating point.
math.pow(x, y)Floating-point power with a finite real result. You can also write x ** y.
math.sum(xs), math.min(xs), math.max(xs)Total, smallest or largest of a list of numbers, or of several numbers: math.max(4, 9, 2). An empty list gives 0 for the sum and none for min and max.
math.clamp(x, low, high), math.sign(x)Keep x within bounds, or get -1, 0 or 1.
math.pi, math.eThe constants π and e. They are values, not functions, so write them without parentheses.

7 // 2 divides and rounds down to 3. 2 ** 10 raises to a power. Both work in Rowan and Bowen.

Random numbers and time

FunctionContract
random.int(low, high)A whole number from low to high, including both.
random.number()A decimal from 0 up to, but not including, 1.
random.pick(items), random.sample(items, n)One random item, or n different random items.
random.shuffle(items)A shuffled copy of the list.
random.seed(n)Make the following random results repeat exactly each run. This helps with testing a game.
time.now()The local date and time as "YYYY-MM-DD HH:MM:SS".
time.clock()Seconds from a fixed starting point. Subtract two readings to time some code.
time.sleep(seconds)Pause the program. Decimals such as 0.5 are fine.

Files, CSV and JSON

FunctionContract
fs.base(), fs.join(a,b)Entry program’s data folder, or two joined path components.
fs.exists(path), fs.list([folder])Test existence, or list immediate child names in sorted order. The default folder is ".".
fs.mkdir(path)Create a directory and any missing parents.
fs.read(path), fs.write(path, text)Read or write UTF-8 text. A leading UTF-8 byte-order mark is accepted on read.
json.parse(text), json.format(value)Decode JSON, or encode a value as indented JSON. JSON null maps to none. Typed records encode as objects and decode as plain maps.
json.read(path), json.write(path, value)Read or write a JSON document.
csv.parse(text[, Schema]), csv.read(path[, Schema])Read CSV with a header. With no schema every cell is text. With a record schema, match headers by name and convert each cell.
csv.format(rows), csv.write(path, rows)Encode rows with the same field names. At least one row with columns is required to infer the header.

CSV supports quoted fields, commas and multiline fields. A typed read requires the exact set of column names, in any order. Boolean cells accept true or false in any letter case. List and map cells use JSON. An any cell is read as text. A blank or duplicate header, mismatched field count or failed conversion produces an error. Data-writing functions replace the target via a temporary file in the same directory. Create missing directories first with fs.mkdir. Programs operate with your normal file permissions.

Save data between runs

Run the notebook example with add "Practice endgames" and then with list. The first command stores a JSON list in examples\notebook-data.json. The second starts a fresh Rowan process and opens that same file. Read its source to see args, assert, fs.exists, json.read and json.write working together.

Projects and implementation

FileWhat to explore
examples/hello.rowanA two-line interactive greeting.
examples/tour.rowanA self-checking tour of text formatting, list helpers, set +=, unpacking, randomness and recursion.
examples/practice/desk.rowanA persistent practice log with menus, forms, tests and an HTML chart.
examples/robot_lab.rowanFind the best battery and motor combination under a budget, using two ordered objectives.
examples/cube_report.rowanTyped CSV, grouping, nested aggregation and table output.
examples/four_queens.rowanFinite search, early pruning and a board display.
examples/club/main.rowanA multi-file project with exported record constructors and a join.
examples/notebook.rowanA command-line application that persists notes.
examples/algorithms.rowanBinary search and a closure that remembers its counter.
examples/debug_me.rowanAn intentional failing assertion for the debugger tutorial.

How the interpreter works

source/syntax.py tokenizes Rowan source, records file/line/column locations and builds a syntax tree with a recursive-descent parser. source/runtime.py executes that tree using lexical environments, explicit call frames, a query engine and a depth-first search evaluator. source/values.py defines values and update rules. source/stdlib.py supplies the primitive I/O and library functions. source/debugger.py listens at execution points and evaluates inspection expressions with the same Rowan parser. rowan.py connects those pieces to the command line.

Python hosts the interpreter. Your programs use Rowan’s grammar, rules and library. Each Rowan program runs synchronously in one process. Studio launches a separate interpreter process for each run. Query data and complete solve results live in memory. Use solve first when one solution is enough. Function recursion uses the host call stack. Application modules are local source files. The bundled standard library covers the APIs listed in this handbook.

For the formal syntax, open grammar.ebnf. The editable source for this handbook is Handbook.md. After editing it, rebuild the HTML pages with python guide\build_handbook.py. No extra tools are needed. The tests in tests/test_rowan.py, tests/test_improvements.py and tests/test_studio.py exercise the language, library, optimization, CLI and Studio workflows. Add a small Rowan program with an assert to specify a behavior, then run .\rowan.cmd test after modifying the implementation.

To add a library function, edit source/stdlib.py. Each entry names a Python function and its minimum and maximum argument counts. Raise Fault("message") to report a problem to the Rowan program. The message should tell the reader what to do.

Troubleshooting

SymptomAction
“Rowan needs Python” or a runtime setup messageRun Setup Runtime.cmd in the extracted folder or use an installed Python 3.10+. If using a new system install, open a fresh terminal.
Studio does not open a tabKeep the launcher running and paste its printed local address into your browser. A refresh reconnects to an active run in the same session.
A program saves with a .txt extensionIn Notepad choose Save as type → All files, name it example.rowan and select UTF-8.
A data file cannot be foundPrint fs.base(). Put the data there or use an absolute path. For a missing module, check its path relative to the importing file.
A query complains about text where it expected numberscsv.read(path) returns text cells. Pass a record declaration to the reader or call toNumber in a projection.
“Expected a new line”Put each statement on its own line or separate statements with ;. Inside a map, separate fields with commas.
A breakpoint is skippedUse list to verify that the line contains an executable statement, multiline stage or search clause. Make sure control reaches it.
You need to stop a long runUse Ctrl+C in the terminal. In the debugger, q ends a paused session.
“Too many nested calls”A function calls itself without stopping. Check that every path reaches a return that does not call the function again.
“is a reserved word”Rename the binding. Words such as count, sum, min, max, first, select, where, sort and group are pipeline stages.
Random results change every runCall random.seed(1) once at the start while testing. Remove it when you want fresh results.