Guide › Full reference
Full reference
The complete, formal syntax and semantics of Turtle, as implemented by the token/lexer/ast/parser/object/evaluator packages. For a gentler, example-first introduction see tour.md; for the standard library see the library docs.
Notation below: code is a literal token; <angle-brackets> is a non-terminal; [x] is optional; {x} is zero-or-more; | is alternation.
Lexical grammar
- Files: Turtle programs, libraries and tests end in
.turtle(report.turtle,lib/utils.turtle,test_orders.turtle). The older ending.trtis accepted too, everywhere.turtleis:import utilsfindsutils.turtleorutils.trt(both at once is an error, so an import never quietly picks one), andturtle testrunstest_*.trtfiles as well. - Comments:
// ...runs to end of line.//* ... *//is a block comment that may span multiple lines. Both are stripped by the lexer. - Identifiers:
<letter|_> {letter|digit|_}, where a letter may be any language's (café,größe,名前). Turtle's own names are all lowercase (isempty,scriptfolder,sql_open). - Numbers:
<digits>(integer) or<digits>.<digits>(float), and scientific notation, always a float:1e-18,2.5e6,6.02E+23. - Strings:
"double"or'single'quoted (the same kind of string; inside single quotes a"needs no escape). Escapes:\n,\t,\",\',\\,\{,\}.{<expr>}inside a string is interpolation (see §Strings). A string may go over several lines (SQL, a message): the line breaks are part of the text. - Raw strings: `
backtickskeep every character as typed: no escapes, no interpolation, and they may span lines. For patterns (\d{3}) and Windows paths (C:\new\table`). A raw string can't hold a backtick. - Booleans:
true,false. - None:
none— the single "no value" value (typeNONE). - Reserved words (cannot be used as identifiers; each is explained in Keywords):
true false none show if else def end loop return list set map import sys to from at of is add change remove delete sort reverse insert min max length read write append directory break continue give in assemble safe handle fail warn div scroll. Type names used afterchange ... to—integer,float,string,ascii,char,hex— are not reserved; like method names (get,union, ...) they're plain identifiers whose meaning is only special right afterto.
One statement per source line, except:
- Blocks with their own begin/end markers: function, if and loop bodies,
[write]/[append]/[read]/[directory]blocks. Anything in brackets may go over as many lines as it likes: lists, sets, maps, matrices, a call's or a method's arguments, an import's names, a function's parameters, an assembled type's fields. A comma before the closing
]is allowed, so each item can have a line of its own:import time [ now, today, ] order = Order[ "pen", 3, ] prices = map [ "pen": 150, "ink": 400, ]In an if-header, a
[that ends its line opens the body (if ] ready [), so a call there starts its arguments on the[line:if ] ok[x] [.- An operator at the end of a line carries the expression on to the next:
total = a +thenbon the next line. An operator at the start of a line is never a continuation of the line before. - Text, which may go over several lines.
Keywords
Every word Turtle reserves, what it does, and where it's explained. A reserved word can't name a variable or a function (length = 3 is an error that says so).
Reserved words
| Word | What it does | Example | See |
|---|---|---|---|
add | adds an item to a list or set (or a key to a map) | add 4 to nums . | Data structures |
append | adds lines to the end of a file | [append] log.txt ... [end] | Files |
assemble | names a kind of value with fields | assemble Order [item, qty] | Assembled types |
at | calls a method on the value before it | nums at get[0], name at upper | Expressions |
break | leaves a loop | break | Return / break / continue |
change | converts a value to another type | n = change "42" to integer | Type conversion |
continue | goes on to a loop's next pass | continue | Return / break / continue |
def | defines a function | def total[a, b] ... def [end] | Functions |
delete | removes a key from a map | delete "Bo" from ages . | Data structures |
directory | lists a folder's entries | [directory] data to names [end] | Files |
div | whole-number division | 7 div 2 is 3 | Expressions |
else | the other branches of an if | else if ] x > 2 [, else ] | Conditionals |
end | closes a block | def [end], if [end], [loop][end] | Conditionals |
fail | raises your own error | fail "no stock" | Errors |
false | the boolean false | done = false | Lexical grammar |
from | in sentences: where from | remove 1 from nums . | Data structures |
give | makes a function without a name | x give x + 1, [a, b] give a + b | Anonymous functions |
handle | the part of a safe block that runs on an error | handle [file] e . | Errors |
if | runs code when a condition holds | if ] x > 1 [ ... if [end] | Conditionals |
import | brings in a library or your own file | import sql, import lib/utils, import time [now] | Modules |
in | the items a loop goes through | [loop][x in nums] | Loops |
insert | puts an item into a list at a position | insert 9 to nums at 0 . | Data structures |
is | assigns, in sentence form | r is nums at get 0 . | Expressions |
length | how many items or characters | length of nums | Data structures |
list | makes a list | list [1, 2, 3] | Data structures |
loop | repeats code | [loop][x in nums], [loop][i = 0; i < 3; i++] | Loops |
map | makes a map of keys to values | map ["a": 1] | Data structures |
max | the largest item (max of nums, or max[nums], or max[a, b]) | max of nums | Data structures |
min | the smallest item (min of nums, or min[nums], or min[a, b]) | min of nums | Data structures |
none | no value | x = none | None |
of | a field or key of a value | qty of order, length of nums | Assembled types |
read | reads a file's lines | [read] notes.txt to lines [end] | Files |
remove | removes an item from a list or set | remove 4 from nums . | Data structures |
return | gives a function's answer back | return total | Return / break / continue |
reverse | reverses a list in place | reverse nums . | Data structures |
safe | runs code that may fail, with handle for the errors | safe ... handle [] e . ... safe [end] | Errors |
scroll | steps a value goes through, in order | x is scroll 3 into add1, double . | Scrolls |
set | makes a set: no repeats | set [1, 2] | Data structures |
show | prints values | show "total: ", n . | Show |
sort | sorts a list in place (import sort for more) | sort nums . | Data structures |
sys | runs a shell command | sys ls -la | Shell escape |
to | in sentences: where to, or what into | add 4 to nums ., change x to integer | Type conversion |
true | the boolean true | done = true | Lexical grammar |
warn | prints to the error stream (import system) | warn "careful" . | Show |
write | writes a file's lines | [write] notes.txt ... [end] | Files |
Words an import turns on
These mean something only in a file with the import; anywhere else they're ordinary names. In such a file they can't name a function.
| Word | Import | What it does | Example | See |
|---|---|---|---|---|
random | import random | a random value of any shape | random list of 5 integers from 0 to 9 | the random library |
check | import test | one fact a test checks | check total[o] == 45 . | Tests |
verify | import test | a rule over every item | verify evens[nums] each x give x % 2 == 0 . | Tests |
validate | import test | a rule over random inputs | validate evens[nums] with nums as list of integer that ... | Tests |
log | import log | a log line, with a level | log warn "disk at ", pct, "%" . | Logging |
matrix | import linear | makes a matrix | m = matrix [1, 2; 3, 4] | the linear library |
Words special only in one place
Ordinary names everywhere else, so a variable can still be called put or here.
| Word | Where | Example | See |
|---|---|---|---|
put | first on a line: replace an item | put 9 to nums at 2 ., put 9 to m at 1, 2 . | Data structures |
into | in a scroll: the steps follow | x is scroll 3 into add1, double . | Scrolls |
here | in a scroll step: the value so far | here at get[0] | Scrolls |
diagnose | a line of its own, or diagnose[...]: look inside | diagnose ... diagnose [end] | diagnose |
hypothesis | hypothesis[...]: try a claim, true or false | hypothesis[prices each p give p > 0] | hypothesis |
reportfile | a variable: also write diagnose and hypothesis reports to a file | reportfile = "checks.txt" | reportfile |
type | after a value: whether it's that kind, true or false | if ] n type integer [ | The kind of a value |
integer, float, string, ascii, char, hex, keys, values | after change ... to | change x to float | Type conversion |
each, any, not, exactly, least, most, pair, that, with, as, matches, fails, close, within | in check, verify and validate sentences | verify xs at least 2 x give x > 0 . | Tests |
debug, info, error | right after log | log debug "x is ", x . | Logging |
theory, abstract, notation, definition, theorem, proof | a theory, and its sections | theory tally ... theory [end] | Theories |
Statement terminators
| Statement kind | Trailing . |
|---|---|
Assignment (x = expr) | No |
Input (x = ?, x = ? "prompt") | Optional |
return | No |
| Bare function call statement | No |
show | Yes |
Data-structure statement ops (add/remove/delete/sort/reverse/insert) | Yes |
min of/max of/length of as a statement | Yes |
is ... [at ...] | Yes |
import, sys, break, continue, def/if/loop headers and [end] markers | No |
Assignments have no period; show does.
Example.
x = 1
show x .
show "done" .
1
done
Expressions
Precedence, low to high:
| Level | Operators | ||
|---|---|---|---|
| 1 (lowest) | `\ | \ | ` |
| 2 | && | ||
| 3 | == != | ||
| 4 | < <= > >= | ||
| 5 | + - | ||
| 6 | * / div % | ||
| 7 | unary - ! | ||
| 8 | a method: x at m (works on the value right before it) | ||
| 9 (highest) | primary: literals, identifiers, calls, (...) grouping |
Operators on the same level go left to right: 10 - 4 - 3 is 3.
+ adds two numbers; on two lists, two sets, or two maps it combines them (below); on two pieces of text it joins them. Text and any other value is a type error: "5" + 0 stops the program rather than giving "50", and the message says how to write what was meant. To put a value in text, write it inside the text with {...} ("total: {n}") or change n to string first; to add, change the text to a number first ((change t to integer) + 1). A list, set or map added to anything else, including text or a different kind of collection, is a type error: list [1] + 1 and "n=" + nums stop the program. none only adds to none (see §None). Values taken out of a list add like any other value. - and * require two numbers.
Division has two operators, one for each kind:
| Expression | Result | |
|---|---|---|
7 / 2 | 3.5 | / always gives the exact answer, a float |
6 / 3 | 2.0 | even when it comes out whole |
7 div 2 | 3 | div gives the whole part, an integer |
-7 div 2 | -3 | toward zero |
7.9 div 2 | 3 | works on floats too; still an integer |
7 % 2 | 1 | the remainder |
-7 % 2 | -1 | the remainder that goes with div: (a div b) * b + a % b is a |
Division or div by zero is a math error. % of two integers is an integer; with a float on either side it's a float (10.5 % 3 is 1.5); % by zero is a math error too. (// starts a comment, so Turtle's whole-number division is the word div.) </>/<=/>= work on two numbers or two strings (lexicographic). ==/!= compare numbers by value (1 == 1.0), functions by identity (the same definition), lists element by element in order, and sets and maps regardless of order (set [1, 2] == set [2, 1]). Everything else needs the same type and value, so 1 != "1", none == none, and none never equals 0, "", or "none". The same equality is used for set deduplication and membership and for count/index/find/remove. Map keys can be any value and keep their type: in map [1: "a", "1": "b"] the integer 1 and the string "1" are two different keys, and looping over a map or getkeys gives back integers as integers. Equal values are the same key (1 and 1.0; set [1, 2] and set [2, 1]).
Values show as their type. An integer shows as 4, a float always with a decimal point, 4.0, so 2.5 * 2 shows 5.0. Inside a list, set, map or assembled value, text is quoted so it can't be mistaken for a number: show list [1, "1"] . prints [ 1, "1" ]. Text on its own isn't quoted: show "hi" . prints hi.
Integers have no fixed size: 2 at pow 100 is 1267650600228229401496703205376, and a literal can be as long as you like. The arithmetic is exact (9223372036854775807 + 1 is 9223372036854775808). A result past 10,000,000 bits (about 3 million digits) is a math error, raised before the work is done, so one line such as 2 at pow 10000000000 can't take all the memory; change ... to integer reads at most 1,000,000 digits. Small whole numbers stay on the fast path, so ordinary loops cost no more. Conversions from a float keep the whole part exactly: change 1e19 to integer is 10000000000000000000.
Floats are the usual 64-bit ones. Arithmetic past their range gives inf or -inf, and inf - inf gives nan (show 1e308 * 10 shows inf). A power or a math function past the range is an error instead. Division by zero is always an error.
Truthiness (conditions, &&, ||, !): false, none, 0, 0.0, "", and an empty list, set or map are falsy; everything else is truthy. So if ] matches [ means "if there are any matches". matches at isempty asks the same thing explicitly.
&& and || stop as soon as the answer is known, as in other languages: in x != none && x > 5 the x > 5 only runs when x isn't none, and in found || search[] the search only runs when nothing was found. Either way the result is true or false.
+ and - on two collections of the same kind always make a new one; neither side changes:
| Expression | Result |
|---|---|
list + list | joined, in order |
list - list | the left list without any element that's in the right one |
set + set | union |
set - set | difference |
map + map | all entries; on a key both have, the left map's value wins |
map - map | the left map without the right map's keys (values ignored) |
<expr> at <method> calls a method inside any expression: show name at upper ., w = x at slice[0, 3]. One argument can go without brackets: it's just the value right after the method, so 3 at pow 2 == 9 compares the power, s at contains "a" && ok asks both, and list [x at get 0, 1] is two items. More than one argument goes in brackets (x at slice[0, 3]), except in the statement form, r is x at slice 0, 3 ., which takes them unbracketed.
A method works on the value right before it, with or without brackets. Use ( ) to apply it to a whole calculation:
| Turtle | Means |
|---|---|
a at invert == b at invert | both maps inverted, then compared |
"a" + "b" at upper | "aB" |
"+" + "-" at padright[5] + "+" | "+- +": only "-" is padded |
("+" + "-") at padright[5] + "+" | "+- +": the whole text is padded first |
("a" + "b") at upper | "AB" |
2 + 16 at sqrt * 2 | 10.0 |
nums at get[0] + nums at get[2] | adds two items |
-7 at abs | 7: -7 is one number |
-x at abs | -(x at abs) |
!r at isempty | "r is not empty" |
title of b at upper | the title, upper-cased (title of b is one value) |
The same rule holds in the statement form: r is "a" + "b" at upper . is "aB", like r = "a" + "b" at upper. Methods that give a new value (invert, upper, abs, ...) leave the variable as it was; list, set and map methods that change the collection (add, sort, remove, ...) change it, as before.
Order of operations, highest first: ( ); a method (at); - and ! in front of a value; * / div %; + -; < > <= >=; == !=; &&; ||. Operators of the same level go left to right: 10 - 4 - 3 is 3, 100 / 10 / 5 is 2. Expressions can be as long and nested as you like: 1 + 2 - 3 + 4 - (5 + 6) + 7 * 8 is 49, 2 * (3 + 4) * (5 - (6 - 7)) is 84.
Arguments and operators. How far an argument reaches depends on the form:
| Written as | Means | Result for nums = list [10, 20, 30], i = 1 |
|---|---|---|
nums at get i + 1 | (nums at get i) + 1: the method's argument stops before + | 21 |
nums at get (i + 1) | the item after i | 30 |
nums at get[i + 1] | the item after i | 30 |
nums get i + 1 | nums get (i + 1): a sentence call's argument takes the + | 30 |
(nums get i) + 1 | the item at i, plus 1 | 21 |
So: a method (at) takes one value as its bracket-less argument, and a sentence call takes the arithmetic. To give a method the whole sum, use parentheses or brackets. To add to the item, put the call in parentheses.
Function calls: <name>[<expr>, ...] — Turtle uses [...] for call and definition argument lists, not (...). See also sentence-style calls under Functions.
Example.
show 2 + 3 * 4 .
show (2 + 3) * 4 .
show 7 % 3 .
show "n=" + "5" .
14
20
1
n=5
Variables
<ident> = <expr>
<ident> = <expr> .
The closing period is optional, as after a function call; it reads naturally after a sentence: big = nums keep n give n > 10 .
Example.
total = 12
name is "Ann" .
show total, name .
total = total + 1
show total .
12 Ann
13
Input
<ident> = ?
<ident> = ? <string>
Reads one line from stdin and assigns it as a string. With a string, prints it first as the prompt. A closing period is optional:
a = ?
age = ? "Age for {name}? " .
n = change age to integer
The program reads a line from standard input. Here the input is Ann.
Example.
a = ?
show "hello ", a .
hello Ann
Type conversion
change <ident> to <type> . // mutates <ident> in place
<ident> = change <expr> to <type> // expression form, no mutation
<type> is one of integer, float, string, ascii, char, hex, list, set, keys, values, and, in a file that imports linear, matrix. All but list and set are ordinary identifiers, not reserved words — they only mean anything right after change ... to.
The statement form requires the source to be a plain identifier (like the target of add ... to <ident> .) and rewrites that variable's value in place. The expression form works anywhere an expression can — assigned to a different variable, nested inside a larger expression, passed as a call argument — and never mutates its source:
Illustrative. This example waits for keyboard input, so it is shown for reading and is not run as a test.
raw = ? "Enter a number: "
n = change raw to integer
show n + 1 .
Which conversion runs is inferred from the value's current type, so one target name covers both directions of a pair:
| Target | From | Result |
|---|---|---|
integer | string | parsed as base-10, with single underscores allowed between digits ("1_000" is 1000); fatal if invalid |
integer | float | truncated toward zero |
float | string | parsed as a float |
float | integer | widened |
string | integer / float | display form |
ascii | one-character string | its code point, as an integer |
char | integer | the one-character string for that code point |
hex | integer | lowercase hex digits, no 0x prefix |
hex | string | parsed as hex (0x prefix optional) back to an integer |
set | list | a new set: duplicates dropped, each kept where it first appeared |
list | set | a new list, in the set's order |
list / set | the same kind | a copy, so changing it doesn't change the original |
keys | map | a new list of its keys, in order |
values | map | a new list of its values, in order |
list / set | map | its keys (like keys) |
list / set | string | its characters: change "abc" to list is [ "a", "b", "c" ] |
matrix | a list of lists (rows), or of maps (what table_read gives) | a new matrix (import linear) |
list | matrix | a list of its rows, each a list |
Any other combination is a fatal error naming the source and target types.
nums = list [3, 1, 3, 2, 1]
unique = change nums to set // { 3, 1, 2 }
back = change unique to list // [ 3, 1, 2 ]
change nums to set . // nums itself becomes { 3, 1, 2 }
ages = map ["ann": 30, "bo": 25]
names = change ages to keys // [ "ann", "bo" ]
years = change ages to values // [ 30, 25 ]
Example.
n = change "42" to integer
show n + 1 .
show change 3.9 to integer .
show change 7 to string .
43
3
7
Show
show <expr> {, <expr>} .
Each piece is evaluated and written in order, with one space between two pieces. The space is left out where the text on either side already has whitespace, so text that ends in a space keeps its own:
| Program | Shows | ||
|---|---|---|---|
show 3, 2 . | 3 2 | ||
show "total: ", n . (with n = 3) | total: 3 | ||
show "a", "b", "c" . | a b c | ||
show name, "!" . (with name = Ann) | Ann ! | ||
show "{name}!" . | Ann! | ||
| `show n, "\ | ", name .` | `3 \ | Ann` |
show "", "empty first" . | empty first | ||
show list [1, 2], "items" . | [ 1, 2 ] items | ||
show 1 + 1, 2 + 2 . | 2 4 | ||
show "x is ", x, ", y is ", y . (with x = 1, y = 2) | x is 1, y is 2 | ||
show "a", "(", x, ")" . | a (1) | ||
show "did you mean ", name, "?" . | did you mean Ann ? | ||
show "did you mean {name}?" . | did you mean Ann? |
In a show line, a semicolon starts the next item, so a sentence call's commas stay its arguments: show 1 add3 2, 3; " " . prints the sum, then a space. Elsewhere a semicolon is only for loop headers.
Punctuation is set against the value before it: no space goes before , . : ; ) ] } or after ( [ {. A ! or ? is a piece like any other and gets its space. Everything else does too, such as -, /, %, ' or a letter (show "20", "-", "45" . gives 20 - 45). To join pieces with no space at all, write the text with {...} (show "did you mean {name}?" ., show "{a}-{b}" ., show "x={n}" . gives x=3) or use + between two pieces of text (show "x=" + name .).
Floats show the shortest text that reads back as the same float. So 0.1 + 0.2 shows 0.30000000000000004, and list [1, 2, 3] process x give x * 0.2 shows [ 0.2, 0.4, 0.6000000000000001 ]. Very big and very small floats show in scientific notation: 1e+16 and up, and below 0.0001 (1e-05). Writing to a file (JSON, CSV) or a database keeps every digit as well.
Floats compare exactly: 0.1 + 0.2 == 0.3 is false, because the two are different floats (the first is 0.30000000000000004). Sets, map keys, contains and index agree: two floats are one key only when they are the same float. A matrix's == is exact too. For a match within a margin, use is close to in a test, or round first (x at round[2] == y at round[2]). For a fixed number of places on screen, use x at fixed[2] ("0.30").
Example.
show "total: ", 12, " items" .
show list [1, 2] .
total: 12 items
[ 1, 2 ]
Strings
{<expr>} inside a string puts the value of <expr> there, shown the way show shows it:
import strings
assemble Point [x, y]
p = Point[1, 2]
nums = list [1, 2]
w = "word"
name = "Ann"
qty = 3
name = "Ann"
show "Hi {name}, you have {qty * 2} items" . // Hi Ann, you have 6 items
show "{x of p} {nums at len} {w substring 3}" .
show "a plain \{brace\}" . // a plain {brace}
- Any expression works inside the braces except one that contains a quoted string: the quote would end the outer string. Put the text in a variable first. Spaces inside are fine:
{ name }. - It works in every string, single- or double-quoted:
show, assignments,return,?prompts, and the lines of a[write]/[append]block. Plain braces. A
{is just a brace when the next non-space character is a quote or}, or nothing follows it. So JSON never needs escaping, and"{}"is{}:data = load['{"name": "Ann", "tags": ["a", "b"]}'] show "{}" . // {}A number alone in braces, such as
{2}, is read as the value 2 and gets a note: write\{2}to keep the braces as text.\{is always a plain brace; use it for other text with braces, like"set \{1, 2}". A{with no closing}or an unfinished expression is a parse error. A}on its own is plain text.
Backticks make a raw string: what's between them is the text, exactly. { and \ are ordinary characters, and the string may run over several lines:
n = 5
show `{n} stays` . // {n} stays
show `C:\new\table` . // C:\new\table
digits = `\d{3}-\d{4}` // a pattern (import pattern)
Single quotes make text full of double quotes readable: 'She said "hi"', '{"a": 1}'. They're the same strings as double-quoted ones, with the same escapes and interpolation; only the quote that ends them differs.
Return / break / continue
return <expr>
return
break
continue
return ends the current function call; the value is usable directly at the call site. A bare return (nothing else on the line), or reaching the end of the body without a return, yields none. break/continue only affect the nearest enclosing loop; outside a loop they're a no-op.
continue skips the rest of a pass; break leaves the loop.
Example.
[loop][i in list [1, 2, 3, 4, 5]]
if ] i == 2 [
continue
if [end]
if ] i == 4 [
break
if [end]
show i .
[loop][end]
1
3
Functions
def <name>[<param>, ...]
<statement>
...
def [end]
Call: <name>[<expr>, ...]. Written as key: value pairs, the arguments are one map: options["--out": "a.csv", "-v": false] is options[map ["--out": "a.csv", "-v": false]]. Each call gets a fresh scope seeded with its parameters. At most 100,000 calls can be in progress at once; past that is a "recursion too deep" error (usually a recursive function missing its stopping case). Scoping is lexical: a name that isn't a parameter or local is looked up in the scope the function was defined in — for a top-level function that's the global scope, so every function body can read top-level variables; it never sees the caller's locals. A parameter/local of the same name shadows the outer one. Assignment always writes to the call's own local scope, never an outer one, so x = ... inside a function can't clobber a global x — it just shadows it for the rest of that call. When a function assigns a name that the file also sets at top level, Turtle prints a note where the assignment is (once per name and function), because that assignment makes a local and the top-level value stays the same. The editor shows the same note. Reading the outer one to assign it, as in count = count + 1 with no local count yet, is an error that says what to do instead: give the function the value and return the new one, or keep it in a list or map. Mutating an outer list/set/map via a data-structure statement or method call does affect it, since that mutates the same underlying value rather than rebinding a name. The body can call any other top-level function, including itself, recursively. Argument count must match parameter count.
A function can be called before its def. A file's top-level functions are all defined before its first line runs, so the main code can come first and the helpers below it, and functions can call each other in any order:
orders = load_orders["orders.csv"]
report[orders]
def load_orders[path]
...
def [end]
Only functions work this way. Everything else still runs top to bottom: a variable is set when its line runs (a function called early can't read a global set further down), and so is an assembled type. A def inside a function is made when its line runs. A layout that reads well: imports, then settings, then the main code, then the functions.
Give back, don't change outer variables
A function can read a top-level variable, but x = ... inside it makes a new local x; the outer one stays as it was. To change a value, give the new one back and assign it where you call:
total = 0
def addtax[amount]
return amount * 1.2
def [end]
total = addtax[100] // the caller decides what changes
For several results, give back a list or an assembled value:
scores = list [4, 9, 2]
def minmax[nums]
return list [min of nums, max of nums]
def [end]
r = minmax[scores]
low = r at get[0]
Lists, sets and maps are shared, not copied, when passed in, so a statement that changes one (add 4 to nums ., nums process x give x * 2 .) inside a function changes the caller's too. That's handy for "fill this list", but giving back a new collection (return nums process x give x * 2) keeps the function's effect visible at the call.
Functions are values
A function's name, used without [...], is the function itself: it can be assigned, passed as an argument, returned, and compared with ==. Calling <name>[...] resolves name first as a variable holding a function, then as a top-level function, then as a builtin (now, sleep).
def double[x]
return x * 2
def [end]
def apply[f, v]
return f[v]
def [end]
show apply[double, 21] . // 42
g = double
show g[4] . // 8
A result must be stored before it's called — g = make[] then g[]; make[][] isn't valid syntax.
Closures
A def inside a function body defines a closure: a local variable holding a function that remembers the scope it was defined in, so it can read the enclosing call's parameters and locals even after that call has returned. Nested defs are local to their enclosing call, not global.
def make_adder[n]
def adder[x]
return x + n
def [end]
return adder
def [end]
add5 = make_adder[5]
show add5[1] . // 6
Captured variables are read-only by assignment, following the same rule as globals: n = ... inside adder creates a local n instead of changing the captured one (and n = n + 1 is an error). To keep mutable state in a closure, capture a list/set/map and mutate it in place:
def make_counter[]
counts = list [0]
def inc[]
c is counts at pop .
c = c + 1
add c to counts .
return c
def [end]
return inc
def [end]
tick = make_counter[]
show tick[] . // 1
show tick[] . // 2
Anonymous functions: give
x give <expr> // one parameter
[a, b] give <expr> // several, bracketed like a def
[] give <expr> // none
[x] give // block form: a whole body, closed by give [end]
<statement> ...
give [end]
give makes a function without a name. It's a value like any other function, and it can read the variables around it (it's a closure).
def apply[f, v]
return f[v]
def [end]
double = x give x * 2
show double[4] . // 8
plus = [a, b] give a + b
show apply[x give x + 1, 3] . // 4
big = [x] give
if ] x > 3 [
return true
if [end]
return false
give [end]
The expression form's body runs to the end of the expression, so inside a call's [...] it stops at the next , or ].
Methods as functions
A method can also be called like a function, the value it works on going first, and so also as a sentence: trim[s] and s trim are s at trim; round[x, 2] and x round 2 are x at round[2]; get[nums, 0] is nums at get[0]. A function of the program's own, or a library's, with the same name comes first. Methods that need an import (round needs import math) need it in every form.
Sentence-style calls
<variable> <function> [<arg>, ...]
calls <function>[<variable>, <arg>, ...]: the variable on the left becomes the first argument. It works with any function: your own, an imported one, or a builtin like data's process.
def scale[xs, f, k]
return xs process f
def [end]
import data
nums = list [1, 2]
nums process x give x + 1 . // process[nums, x give x + 1]
r = nums scale x give x + 1, 10 // scale[nums, x give x + 1, 10]
show nums sum . // sum[nums]
- The left side is a variable name, a literal (
"lo" isinstring line,list [1, 2] join ","), or a call's result (big = copy[nums] process x give x * 10processes a copy). - An argument takes in arithmetic, so
"abc" find "c" - 1isfind["abc", "c" - 1], andnums get i + 1isget[nums, i + 1]. To do arithmetic on a sentence's result, store it first (i = "abc" find "c", theni - 1) or use brackets (find["abc", "c"] - 1). - A comparison,
&&or||ends the argument and works on the call's result, as in most languages:if ] "urt" isinstring s && ok [ // ("urt" isinstring s) && ok done = nums sum > 100 || late // (nums sum > 100) || late x = a solve b == y // (a solve b) == y - A
givefunction takes the rest of its line, as a lambda does in other languages:nums keep n give n > 2 && n < 9keeps the numbers between them. When more follows a call that has one, use brackets:count_where[nums, n give n > 2] >= 5. - A negative first argument works when the
-is attached to it:s substring -5. A spaced-(a b - 1) or one attached to the name (a b-1) means subtraction. ;ends a call's arguments insideshow. With a comma, the next item belongs to the call; with;, it is a separate item:def fix[a, b] return a + b def [end] x = 1 show x fix 2 ; "The answer" . // 3 The answer show x fix 2, "The answer" . // error: fix expects 2 argument(s), got 3Outside
show,;is not a separator:y = x fix 2 ; 10is an error.- A trailing
.is optional when the call is a whole statement. a bis ambiguous with a module-qualified name (time now). It's settled when the code runs: ifais an imported module, it's that module's function; ifais a variable, it's a sentence-style call. A name that's both is a fatal error.- Outside brackets, a sentence's arguments run to the end of the expression,
,-separated:show t substring 0, 5 .. Inside[...](call arguments, list/set/map literals) it takes one argument, so the commas stay the outer list's:check["x", t find "W", 7]ischeck["x", find[t, "W"], 7]. For two or more arguments there, use the bracket form:substring[t, 0, 5]. - To call an imported function qualified in this style, use the bracket form instead:
data process[nums, f].
Every argument must be given. A call must pass a value for each parameter. A def line has no default values, so def f[a, b = 2] is an error, and a call that leaves out an argument stops with "expects 2 argument(s), got 1". The usual stand-in is none: the caller passes none, and the function puts its own value in its place. A function can also take its settings in a map and read each key with a fallback. Library settings work differently: they are variables set in the import line or changed inside a call. See Modules.
Ways to call a function
Turtle lets a call be written in more than one form. Each form has the same meaning, so a program can use the form that reads best for the task:
| Form | Example | Meaning |
|---|---|---|
| bracket | apple[1, 2] | the arguments inside [ ], separated by commas |
| value first | 1 apple 2 | the value before the name is the first argument |
| name first | apple 1, 2 | the arguments follow the name, separated by commas |
All three give 3 for an apple that adds its two arguments. The bracket form is the clearest when a call sits inside a larger expression, and the name-first form reads most naturally as a plain statement.
The semicolon ; marks where a call's arguments end. It is used in two places:
- In
show,;ends the arguments, and the item after it is printed separately:show apple 1, 2; " is the sum" .prints3 is the sum. - Inside
[ ](a list, set, map or call's brackets),;ends a call's arguments, and it also separates items:list[apple -4,2; apple 3,2; 1,2,3]is[ -2, 5, 1, 2, 3 ]. A comma may follow the;, as in;,.
Without a ;, a name-first call inside brackets takes every comma after it, so list [apple 1, 2] is [ 3 ].
Calls with the arguments after the name
<function> <arg>, ...
calls <function>[<arg>, ...], with no value before the name. It works for any function, including one the program defines, and in every place a value can go:
def apple[a, b]
return a + b
def [end]
show apple 1, 2 . // apple[1, 2]: 3
show apple "a", "b" . // apple["a", "b"]: ab
x = 5
r = apple x, 10 // a variable first: apple[x, 10]
show r . // 15
show apple 1, 2 + 3 . // the arithmetic is part of the argument: apple[1, 5]: 6
show apple 1,2; " is the sum" . // in show, ';' ends the arguments: 3 is the sum
- The first argument may be a literal (a number, text,
true,false,none, or alist,setormap), or a variable. Each argument may use arithmetic, as inapple 1, 2 + 3, andtens i div 3istens[i div 3]. - A negative first argument works for a function the program defines, or for a library function (
abs,sqrt,round...):apple -4, 2isapple[-4, 2]. A name that is a variable is read as a value, sox -1is subtraction. A negative argument to a function value (
f = x give ..., an alias, or a function passed in as a parameter) uses one of these forms, each verified:f = x give x * 3 g = f show f[-1] . // -3, the brackets show -1 f . // -3, the value first show -1 g . // -3, the value first, for an alias show f - 1 . // subtraction: spaces on both sidesf -1with no space before the-and a function value is read as subtraction and is an error whenfis a function value, so use one of the forms above.- In
show, a comma followed by a name starts the next item:show one x, y .is the callone[x]and theny, soonetakes one argument. A comma followed by a literal stays an argument (show apple x, 10 .isapple[x, 10]). A;always ends the arguments:show apple 1, 2; "x" .. Inside
[...](a list, set, map or call's brackets), the commas after a call are its arguments until a;ends them. The;also separates items, so a list can be written with;between calls, and;,works too:def apple[a, b] return a + b def [end] show list [apple -4,2;] . // [ -2 ] show list[apple -4,2; apple 3,2; 1,2,3] . // [ -2, 5, 1, 2, 3 ] show list [apple 1,2;, apple 3,4;, 5] . // [ 3, 7, 5 ]Without a
;, all the commas belong to the call, solist [apple 1, 2]is[ 3 ], and a call with too many arguments reports the count. A plain;between values (list [1; 2]) is still an error.- The sentence form
x fix 2inside[...]still takes one argument, as above. - A leading
(or[is not part of the form:apple (1)is an error. Use brackets. - A
.is optional at the end of a whole statement:apple 3, 4on its own line callsapple.
Assembled types
assemble <Name> [<field>, ...]
<Name>[<expr>, ...] // make one: exactly one value per field, in order
<field> of <expr> // read a field
<field> of <expr> = <expr> // change a field
assemble declares a named type with fixed fields, and <Name> becomes its constructor: a function that takes one value per field.
assemble Order [item, qty, price]
o = Order["pen", 3, 1.5]
show o . // Order { item: "pen", qty: 3, price: 1.5 }
show qty of o * price of o . // 4.5
qty of o = 10
- Fields hold any value, including other assembled values. Field access chains right to left:
x of finish of lineisx of (finish of line), andx of finish of line = 7changes it.ofbinds tighter than any operator, soqty of o * price of omultiplies two fields.length of/min of/max ofbind the same way. ofwithgetandslice. Thegetpicks the item first:title of books at get[0]is the title of the first book, andtitle of books at get[0] at upperupper-cases it. Other methods work on the field:name of p at upper. To index inside a field, name it first:tags = tags of book, thentags at get[0].ofreads map keys too:title of rowisrow at get["title"](a missing key is an error of kindkey), andtitle of row = "Emma"sets it. Handy for SQL rows:title of rows at get[0].- Errors name the fields. A wrong number of values gives "Order needs 3 value(s), one per field (item, qty, price), got 2". An unknown field gives "Order has no field "prise" (its fields: item, qty, price)". Using
ofon a value that isn't assembled is also an error. - Assembled values are references, like lists and maps: after
b = a, changing a field throughbchangesatoo.data'scopy[a]makes an independent copy. - Equality: two values are
==when they come from the sameassembledeclaration and their fields are equal. Same-named types from different declarations are never equal. Equal values are one element in a set and the same map key. - The constructor is a function, so it follows the function rules: a top-level
assembleis exported by its module and imported like any function (import shapes [Point],shapes Point[1, 2]on a clash); one inside a function body is local to it;mk = Orderstores it as a value; andshow Order .printsassemble Order. - Field names must be distinct, and can't be reserved words.
Changing a field. A field is changed by an assignment that names it, and the assembly is changed in place, so every name for it sees the change. A function that receives an assembly can change its fields too:
assemble Order [item, qty, price]
orders = list [Order["pen", 3, 1.5], Order["ink", 1, 4.0]]
def discount[o, pct]
price of o = price of o * (100 - pct) / 100
def [end]
discount[orders at get 0, 10]
show orders at get 0 .
qty of (orders at get 1) = 2
show orders at get 1 .
A field name that the assembly does not have is an error that lists the fields it has. A field's value is not checked against any type, so keep each field's type consistent in your own code.
The kind of a value: typeof, type
typeof[x] gives the kind of any value as text, and needs no import: "integer", "float", "string", "boolean", "list", "set", "map", "date", "none", "function", "error", an assembled value's type name ("order"), or "assembled type" for a type itself.
<value> type <kind> is true or false, and reads as a condition:
assemble order [item, qty]
o = order ["tea", 2]
show typeof[o] . // order
if ] o type order [ ... if [end]
if ] n type integer && s type string [ ... if [end]
if ] !o type order [ ... if [end] // not an order: ! takes the whole check
The kinds are the ones check ... is takes (see testing.md): integer float number string boolean list set map date none function empty and assembled type names. A kind that doesn't exist (n type intger) is an error. type is only special between a value and a kind, so it still works as a variable name.
Example.
show typeof[3.5] .
show typeof["hi"] .
show typeof[list [1]] .
n = 5
if ] n type integer [
show "n is an integer" .
if [end]
float
string
list
n is an integer
Finding things out: help, stdlib, version
Three names that need no import. help knows every library, function, method and keyword (its keyword text is the Keywords tables here). A variable or function of your own with the same name comes first.
import linear
m = matrix [1, 2, 3; 4, 5, 6]
help[m] // This is a matrix, 2 x 3.
// A matrix's methods, as x at rows:
// rows, columns, shape, get[r, c], ...
// Libraries for it: help["linear"]
help["linear"] // the library, and each function in a line
help["reshape"] // one function in full, with an example
help["list"] // a kind of value's methods
help["if"] // a keyword, from the table above
help["keywords"] // every keyword in a line
help["typeof"] // a function every program has
help[] // every library, and how to ask
libs = stdlib[] // map: library name -> its function names
show libs at get["linear"] at contains["flatten"] . // true
show version . // 1.0.0
help shows its text and gives none. Text names what to look up, so help["resahpe"] says did you mean reshape?. In the REPL the same works without brackets: help m, help linear.
Example.
show version .
show stdlib[] at getkeys .
1.0.0
[ "config", "crypt", "data", "http", "json", "linear", "log", "math", "pattern", "random", "schedule", "search", "server", "sort", "sql", "strings", "system", "test", "time" ]
Scrolls
The full guide, with the functional and sentence forms side by side, is in scrolls.md.
A scroll is a value going through steps in order, each step's result feeding the next. It reads top to bottom, instead of inside-out like half[double[add1[3]]], and needs no names for the values in between. It always ends with a period, like a sentence.
x is scroll 3 into add1, double, half . // 3 -> 4 -> 8 -> 4.0
x = scroll 3 into add1, double, half . // the period ends it here too
s = scroll add1, double, half . // no starting value: a saved scroll
y is scroll 10 into s . // 11.0
Steps. Outside [ ], a comma starts the next step; inside, commas separate a call's arguments. Count only the values you type yourself:
| Besides the value, the function needs | Write | Means |
|---|---|---|
| nothing | double | double[value] |
| one value | splitby "," | splitby[value, ","] |
| two or more | add_time[here, 30, "days"] | that call, with the value at here |
hereis the value reaching the step. Without it, the value goes first (join[" - "]isjoin[value, " - "]); with it, it goes wherehereis: first, last, in the middle, or inside a list (sql_query[db, "... ?", list [here]]). A step can also be any expression withhere:here * 2,here at get[0].- Methods start with
at:at trim,at upper,at round[2]. - A function works too:
n give n * 5. - A saved scroll used as a step runs its steps right there, in order: with
first = scroll a, b, c .andsecond = scroll d, e .,scroll 1 into first, second, f .isscroll 1 into a, b, c, d, e, f . - Lists: each step gets the whole list (as
sum,join,keepandtable_writewant). For each item, useprocess:process s give s at trim. Saving such a step makes it reusable:trimall = scroll process s give s at trim .
written is scroll "https://api.example.com/users" into
http_get,
load,
keep u give age of u >= 18,
table_write["adults.csv", here] .
- A scroll over several lines ends at its period; inside
[ ]the period goes before the]:typeof[scroll 1 into add1 .]. - A line can be just a scroll, run for what it does:
scroll rows into table_write["out.csv", here] . - A saved scroll is a value of type
scroll: call it on one value (s[3]), give it toprocessorkeep, keep scrolls in lists and maps. heremeans the value of the scroll it's written in. Outside any scroll it's an ordinary name, sohere = scriptfolder[]still works.
none and errors. none is a value like any other: a step that gives back none passes it to the next step, since some functions answer none on purpose (find_first when nothing matches). An error ends the scroll at its step, because the steps after it depend on it. It keeps its own kind (handle [http] still catches a failed http_get), and its message says which step: scroll step 1 of 4 (http_get): ...: 404 Not Found.
Looking inside: diagnose
diagnose traces a scroll or a function: each step's actual value, every none, and the error where one happened. It shows that on the screen, then gives back what it ended with, and it doesn't stop the program, so it can be added to a line to find a problem and taken off again. It needs no import.
| Given | It shows | It gives back |
|---|---|---|
a saved scroll and a value: diagnose[s, 3] or s diagnose 3 | each step and what it returned | the result, or the error |
a scroll written in it: diagnose[scroll 3 into add1, double .] | the same | the result, or the error |
a function and its values: diagnose[double, 21], diagnose[load, text] | what it was given, what it returned, how long it took, the memory it allocated | the result, or the error |
an error from handle: diagnose[e] | its kind and message, and for a scroll each step | the error |
s = scroll add1, double .
x is diagnose[s, 3] .
diagnose s (line 2)
start 3
1 add1 → returned 4
2 double → returned 8
result 8
Each line is a step's number (2, or 2.1 for a step inside a saved scroll used as step 2), the step as written, and what it did:
→ returnedand the value as it was when that step returned, even if a later step changes the same list or map: its size and what's in it, cut short past 60 characters (map of 2: { "total": 100, "fee": 50 },"text"... (82 characters));→ returned nothing (none) is none expected!?: anonewent on to the next step. Was it meant? If not, that step is where to look (a forgottenreturn, nothing found);✗ failed:and the error: the scroll ended here. A step inside a saved scroll says where it sits:scroll step 2 of 2 (here / 0), in step 1 of 1 (s). When the step was givennone, a line under it says where that came from:(it was given none, from step 2), orfrom the start;not reached: the steps after a failure.
x is diagnose[scroll 3 into add1, shownumber, double .] .
show kind of x .
number 4
diagnose scroll (line 1)
start 3
1 add1 → returned 4
2 shownumber → returned nothing (none) is none expected!?
3 double ✗ failed: operator "*" needs two numbers, got none and integer
(it was given none, from step 2)
type
Here diagnose captures both the none (step 2, "is none expected!?") and the error it led to (step 3, ✗, pointing back at step 2), and x holds the error (a value like the one handle gives: kind of x, message of x), so the program goes on. Without diagnose, the same error stops the program, or goes to a safe block, as usual.
- A scroll that ends with
nonegives backnone, marked "is none expected!?". - In a
handleblock,diagnose[e]shows the error and, for a scroll, what each step did, and gives backe. - Only Turtle's errors are traced:
exit[]and Ctrl-C still stop the program. - A program's own function called
diagnosewins over this one. turtle tracealso shows each scroll step's result as the program runs.- Every report ends with
memory, what the step allocated (as dohypothesisreports and each test inturtle test). Seesystemformemory[],sizeof[x]andfreememory[].
Looking inside any code: the diagnose block
diagnose on a line of its own starts a block, ended by diagnose [end]. The code in it runs as usual; diagnose shows each line as it runs, the value each assignment gave, and each loop pass with its names. An error in it is shown and the program goes on after diagnose [end].
nums = list [4, 7]
diagnose
total = 0
[loop][x in nums]
total = total + x
[loop][end]
avg = total / 0
diagnose [end]
show "after: ", total .
diagnose (lines 3-7)
line 3 total = 0 total = 0
line 4 [loop][x in nums]
pass 1: x = 4
line 5 total = total + x total = 4
pass 2: x = 7
line 5 total = total + x total = 11
line 7 avg = total / 0
✗ failed: math error: line 7: division by zero
after: 11
- It shows the first 60 lines, then how many more there were (a long loop).
- Lines of functions called from the block show too, as in
turtle trace. - It ends with
finished, or✗ failed:and the error. turtle fmtindents the block, and the REPL waits fordiagnose [end].
Trying a claim: hypothesis
hypothesis[...] tries something you believe about your data, a function or a theory, and gives back true or false. On a line of its own it also shows a report: whether the claim holds, and when it doesn't, where it breaks. It never stops the program and needs no import.
hypothesis[prices each p give p > 0]
hypothesis prices each p give p > 0 (line 4)
holds no: 2 of 50 items (4%) break it
prices list of 50: [ 4.5, 3.0, -3, 12.0, ... ]
where at 7 -3 (p is -3, which isn't > 0)
at 31 0 (p is 0, which isn't > 0)
took 12µs
Used as a value it only answers, so a program can act on it:
if ] hypothesis[rows each r give r type Sale] [
show "every row is a sale" .
if [end]
The claim is written the way tests write theirs (see Tests), with the same words:
| Claim | Example | The report adds |
|---|---|---|
a fact, any check form | hypothesis[sum[xs] == 1], hypothesis[n is integer], hypothesis[x is close to 1 within 0.1], hypothesis[load[p] fails [file]] | how the sides differ, and the values it read |
about data: each, any, not, at least, at most, exactly | hypothesis[rows each r give qty of r > 0] | how many items break it (and what share), each one's place, value and why; for a rule about kinds, how many of each kind |
| a function, on random inputs | hypothesis[evens[nums] with nums as list of integer that result each x give x % 2 == 0] | the smallest input that breaks it, the answer, why, and the seed to repeat it |
| a theory | hypothesis[share] | each proof case and theorem, and the line of any that fails |
| a theorem, before it goes in the theory | hypothesis[share, theorem result <= 100] | the smallest input it fails on |
| a proof case | hypothesis[share 1 of 4 . is 25.0] | what it gave instead |
| one use of a theory | hypothesis[share 2 of 1] | whether each of its theorems holds for it |
Tests enforce a claim: a failed check fails the test. A hypothesis asks: it's for finding out what's true of your data, and for trying a theorem before you commit it to a theory.
hypothesis[share, theorem result <= 100]
hypothesis share, theorem result <= 100 (line 9)
holds no: it fails on a = 2, b = 1
where on a = 2, b = 1: result is 200.0, which isn't <= 100
proof 2 of 2 hold
seed 678301857
took 211µs
- An error while trying the claim is a
no, with the error and its line as where it broke. Only a misspelled name still stops the program. - Random inputs follow the
seedandcasessettings when the program has them as whole numbers (asimport testmakes them). - A theory's random inputs that it refuses (with
fail) try nothing; the report says how many it refused, so ayesfrom a few inputs shows. hypothesiscan't name a function; a variable can still be called that.
Reports in a file: reportfile
Reports always show on the screen. To keep them too, set reportfile to a file's path (any text: folder + "/run.txt" works); each diagnose and hypothesis report after that is also added to the end of that file, under the time and the line it came from.
reportfile = "checks.txt"
hypothesis[prices each p give p > 0]
x is diagnose[best 1 of sales] .
reportfile = none // the screen only, again
== 2026-10-10 14:32:07 shop.turtle line 2
hypothesis prices each p give p > 0 (line 2)
holds yes: all 50 items follow it
...
Example.
def add1[x]
return x + 1
def [end]
def double[x]
return x * 2
def [end]
r is scroll 3 into add1, double .
show r .
8
Theories
A theory brings a new word into Turtle: how it's written, what it means, and what it promises. Once a file has a theory, its phrases read like the rest of the language.
theory tally
abstract
tally says how many times b appears in the list a.
notation tally b in a .
definition
n = 0
[loop][x in a]
if ] x == b [
n = n + 1
if [end]
[loop][end]
return n
theorem result >= 0
theorem result <= length of a
proof
tally 1 in list [1, 1, 0, 3] . is 2
tally 9 in list [] . is 0
theory [end]
nums = list [1, 1, 0, 3]
tally 1 in nums . // on its own line
c is tally 1 in nums . // its result, named
show "ones: ", tally 1 in nums . // inside other sentences
| Section | What it does | |
|---|---|---|
abstract | required | what the word means, in plain words; help, turtle doc and the editor show it. It should name the word. |
notation | required, one or more | how the word is written. The names the definition uses (b, a) are its values; every other word (in, of, is ...) is fixed. Two values need a word or a comma between them. Inside a phrase whose notation uses of or is, they're the phrase's words: name a value like qty of item first. |
definition | required | the code, with each value by its name; return gives the result |
theorem | optional, any number | something every result satisfies, written with result and the values: a claim (result >= 0), or a sentence as verify reads (result each x give x >= 0, result at least 1 x give x >= 4), with an optional if that says where it applies (result >= lo if lo <= hi) |
proof | optional | lines of setup (any statements, shared by the whole proof) and checks: a use with is and what it gives, or with fails (the use must stop with an error) |
Rules.
- The word follows
theoryand starts every notation. It must be new: not a keyword, a function, a method, a variable or another theory. - A theory comes before its word is used, reading top to bottom. It's written at the top level of a file.
import shapesbrings in that file's theories with its functions;import shapes [tally]names the ones to bring. Two imports with the same word is an error.theory ~nameis a private theory, for its own file, like a~function: a file that imports it can't use its word, except a test file, which can test it.- A library of the standard library can have theories too (written in Turtle, in
evaluator/lib/):import databrings them in. - A value reaches as a sentence call's does: through arithmetic, not past a comparison,
&&or||(tally 1 in nums == 2compares the result). A fixed word ends the value before it. - The section words are special only in a theory, and
theoryonly at the start of a line before a name: elsewhere they're ordinary names. - The word alone is the theory itself, a value:
typeof[tally]is"theory",tally type theoryis true,help[tally]describes it.
A proof can set things up, and check them in turn:
proof
nums = list [1, 1, 0, 3]
tally 1 in nums . is 2
tally 0 in nums . is 1
tally 9 in list [] . is 0
average list [] . fails
A check must start its own line; setup lines run before the next check. A theorem can be a sentence and can have a condition:
theorem result each x give x >= 0
theorem result >= lo if lo <= hi
Where the if condition is false, the theorem says nothing about that input.
A generator as a theory. A phrase can take a function value, as long as its definition calls it: gen[] makes gen one of the phrase's values. So a generator (a function that gives the next value each time it's called) can read like a word:
def make_counter[]
state = list [0]
def next[]
state at put[state at get[0] + 1, 0] .
return state at get[0]
def [end]
return next
def [end]
theory yield
abstract
yield says the next value of gen.
notation yield gen .
definition
value = gen[]
return value
theory [end]
c = make_counter[]
show yield c . // 1
show yield c . // 2
show yield c . // 3
The counter keeps its state in a list, because a function can change a list it holds but can't reassign a variable from outside.
Which names are the phrase's values. A notation's values are the names its definition uses. A name the definition never uses can't be a value, so the phrase won't match. The definition has to read every name the notation puts in the phrase: notation grab n in g . needs n and g in the definition, as a use (g[] counts) or a read.
Checking a theory. turtle test proves the theories of each test file and of the files it imports: every proof case must give what it says, and every theorem must hold for the proof cases and for 100 random inputs made like their values. A definition that refuses an input with fail doesn't count that input against a theorem. A theorem that breaks shows the smallest input that breaks it. A theory with no proof, or an abstract that doesn't name its word, gets a warning. In an ordinary run none of this is checked. See testing.md.
Tip: a proof is optional, and so are proof cases at the edges (empty, 0, negative, one item), but those are checked on every run, while random inputs only find them by chance.
hypothesis[...] isn't written in a theory: a theory's claims are its theorems. It checks a theory from outside: hypothesis[tally], or a theorem before it goes in, hypothesis[tally, theorem result >= 0] (see hypothesis).
Looking inside. diagnose[tally 1 in nums] shows one use: its values, its result, each theorem for it, and how long it took. diagnose[tally] runs the theory's proof and its theorems, as turtle test does, and shows where they fail. Neither stops the program.
Several theories, and theories built from theories. A program may use any number of theories, and a theory's definition may use another theory. The theory used must come first in the file, and a theory must be written at the top level of a file, not inside another theory or a function. Here small_square is written with within and squared:
theory squared
abstract
squared x says the square of x.
notation squared x .
definition
return x * x
theorem result >= 0
proof
squared 3 . is 9
theory [end]
theory within
abstract
within x, lo, hi says whether x lies from lo to hi inclusive.
notation within x, lo, hi .
definition
return x >= lo && x <= hi
theorem result == (x >= lo && x <= hi)
proof
within 5, 1, 10 . is true
theory [end]
theory small_square
abstract
small_square x says whether the square of x lies within 0 and 100.
notation small_square x .
definition
return within squared x, 0, 100
theorem result == (squared x >= 0 && squared x <= 100)
proof
small_square 5 . is false
small_square 3 . is true
theory [end]
show small_square 3 .
show small_square 5 .
None
none is Turtle's "no value". It's what a function returns when it has no return or uses a bare return, and what the time module's sleep[...] returns. It shows as none, is falsy, and equals only itself. none + none is none; none added to anything else ("x=" + none, 5 + none) is a type error, as are other arithmetic and ordering comparisons on none. To put it in text, use interpolation or show: "x={x}", show "x=", x ..
Example.
x = none
show x .
if ] x == none [
show "x has no value" .
if [end]
none
x has no value
Mistakes in the code
When a file has a mistake Turtle can't read past, it shows the first one, with the line and a ^ under the spot, and says how to fix the usual ones:
turtle: report.turtle, line 2: this line needs a '.' at the end
2 | show x
| ^
Only the first is shown: the ones after it are usually the same mistake seen again.
Notes. Some lines are valid but probably don't do what they seem to. Turtle runs them as written and shows a note first (editors underline them):
turtle: note: report.turtle, line 4: at round works on b only, not on the whole / expression; to round the whole value, store it first: v = ... / b, then v at round
A method works on the value right before it, so a / b at round[1] rounds b. And params of req at get["id"] gets "id" from req (the get goes first, as in title of books at get[0]); when that fails, the error says so and how to write it: v = params of req, then v at get["id"]. Habits from other languages get a pointer to Turtle's way: if x > 0 [ (if ] x > 0 [), if ] x = 1 [ (==), x.upper() (x at upper), f(1) (f[1]), for x in ([loop][x in nums]), a block or a quote never closed. Editors show the same message, under the same spot.
This program stops with an error. Turtle names the line and says how to fix it.
Example.
show 1 + "a" .
turtle: line 1: '+' can't join integer and string (1 + "a"): write the number inside the text with {...}, as "total: {n}", or change it to string first
1 | show 1 + "a" .
Errors: safe / handle / fail
safe
<statement> ...
handle [<kind>, ...] <name> .
<statement> ...
safe [end]
fail <expr>
safe runs the code under it. If a statement there hits an error whose kind is listed, the rest of that code is skipped, the error is stored in <name> (any name), and the code under handle runs. Without an error, the code under handle is skipped and <name> is none. Either way, the program carries on after safe [end], which takes no period, like def [end] and if [end].
safe
[read] settings.txt to lines [end]
count = change lines at get[0] to integer
handle [file, number] problem .
show "using defaults: ", problem . // line 2: [read] settings.txt: no such file or folder
count = 10
safe [end]
Kinds (handle [] e . handles every kind):
| kind | for example |
|---|---|
file | a missing file, a file that can't be written, end of input |
number | change "abc" to integer |
math | division or modulo by zero, a float power or math function out of range, sqrt of a negative |
index | list index out of range, pop or min of on an empty collection |
key | map key not found |
name | undefined variable, function, method, module or field |
type | the wrong kind of value ("a" * 2) or number of arguments |
json | text that isn't valid JSON (json library) |
date | text that isn't a date, or a date that doesn't exist (time library) |
http | a web request that failed, or got a 4xx/5xx status (http library) |
sql | a bad query or a database problem (sql library) |
csv | a .csv or .tsv file that isn't well formed (table_read, sql_load, ...) |
test | a failed check, verify or validate (import test; see testing.md) |
pattern | a pattern that isn't valid (import pattern) |
crypt | text that isn't base64 or hex, a wrong passphrase, an unknown algorithm (import crypt) |
schedule | a bad schedulelimit or setting, a command that can't start, queryall on SQLite (import schedule) |
server | a port in use, a bad route, status or port (import server) |
config | a settings file that isn't well written, or a value it can't hold (import config) |
scroll | a scroll step that isn't a function or scroll, or a scroll inside itself |
linear | matrices of the wrong size for each other, a singular matrix, a non-symmetric matrix for eigen (import linear) |
custom | your own, from fail |
An error of a kind that isn't listed isn't handled: it goes on to an enclosing safe, or stops the program as usual. So does an error in the code under handle itself. A kind that doesn't exist (handle [maths] e .) is a parse error.
The error value shows as its full message (show e . prints line 2: division by zero), and has three parts: kind of e ("math"), line of e (2), file of e ("report.turtle", or "lib/utils.turtle" for an error inside an imported module) and message of e ("division by zero"). For an error inside a scroll, diagnose[e] shows what each step did (see Scrolls). It's truthy, and still set after safe [end].
Where. An error inside an imported module names its file: lib/utils.turtle line 2: division by zero. One in the main script just says line 2: .... This holds whether the program stops on it or a handle shows it, and for parse errors in a module too.
fail <expr> raises an error of kind custom whose message is the value of <expr>. Like return, it takes no period. Unhandled, it stops the program with that message.
def withdraw[amount]
if ] amount > balance [
fail "not enough money"
if [end]
return balance - amount
def [end]
- Errors raised inside function calls, however deep, reach the
safearound the call. Variables set before the error keep their values. return,breakandcontinueundersafeorhandlework as usual.- The error variable follows assignment rules: inside a function it's local.
- Parse errors are never handled; neither is
system'sexit[code].
Example. safe runs code that may fail. The first handle catches a failed conversion; the second catches an error the program raises with fail:
safe
x = change "abc" to integer
show x .
handle [] e .
show "could not convert" .
safe [end]
safe
fail "no stock"
handle [] e .
show "error: ", e .
safe [end]
could not convert
error: line 8: no stock
Conditionals
if ] <expr> [
<statement> ...
{else if ] <expr> [
<statement> ...}
[else ]
<statement> ...]
if [end]
Note the reversed brackets around the condition: ] then the condition then [.
Nesting: write a nested if/else-if/else chain as a statement inside an enclosing clause's body, with one extra leading [ on every keyword of the nested chain:
[if ] <expr> [
...
{[else if ] <expr> [
...}
[[else ]
...]
A nested chain has no [end] of its own — it implicitly ends the moment a clause at the same-or-shallower bracket depth appears. This generalizes to arbitrary depth by adding another leading [ per level (only depth 0 and 1 appear in any known real program).
Example.
n = 7
if ] n > 10 [
show "big" .
else if ] n > 5 [
show "medium" .
else ]
show "small" .
if [end]
medium
Loops
[loop][<header>]
<statement> ...
[loop][end]
<header> is one of:
<ident> = <expr> ; <expr> ; <post> // C-style: init; condition; post
<expr> // while-style: condition only
<ident> in <expr> // for-each
<ident>, <ident> in <expr> // for-each with index or key
For-each walks a list or set (each element), a string (each character), or a map (each key). With two names it gives index, element, or key, value for a map:
nums = list [1, 2]
ages = map ["Ann": 30]
[loop][x in nums]
show x .
[loop][end]
[loop][name, age in ages]
show name, " is ", age .
[loop][end]
It walks a snapshot of the collection, so adding to or removing from it inside the loop can't make it skip or repeat elements. break, continue, and return work as in the other loops.
Loop names (x, or k, v) belong to the loop: a variable of the same name outside isn't touched, and they're gone once the loop ends. Each pass has its own copy, so a function made inside the loop (add [] give x to fs .) keeps the value it saw. Every other assignment in the body works as if the loop weren't there: t = t + x updates t outside.
where <post> is <ident>++, <ident>--, or <ident> = <expr>.
Every [loop][...] — nested or not — requires its own matching [loop][end]; there is no shared-closer shortcut. The induction variable (C-style form) is a real, live variable, visible and updated in show/ expressions on every pass. Like for-each names, it belongs to the loop: a nested loop reusing the same name doesn't clobber its parent's counter, an outside variable of that name is untouched, and it's gone after the loop.
Example.
[loop][i = 0; i < 3; i++]
show i .
[loop][end]
nums = list [5, 7]
[loop][n in nums]
show n .
[loop][end]
0
1
2
5
7
Data structures
See the library docs for full method tables. Declaration:
<ident> = list [<expr>, ...]
<ident> = set [<expr>, ...]
<ident> = map [<expr>:<expr>, ...]
Statement-form operations (all require a trailing .):
add <expr> to <ident> .
add <expr> to <ident> at <key> . // map: a new key gets the value; an existing one changes by its type (5 + 12 is 17)
add <expr> to <ident> at <position> . // list of lists: adds to the item there
remove <expr> from <ident> .
delete <expr> from <ident> . // map only
sort <ident> .
reverse <ident> .
insert <expr> to <ident> at <expr> .
put <expr> to <ident> at <expr> . // replaces the item there (list), or sets the key (map)
length of <expr> . // prints
min of <expr> . // prints
max of <expr> . // prints
min[<expr>] . or min[<a>, <b>, ...] . // the same as min of, without of; max[...] likewise
Method-call form:
<ident> is <expr> [at <method> [<expr> {, <expr>}]] .
sort puts numbers in number order and text in character order (capitals first). A list of lists sorts element by element, then by length: [2, "c"] comes before [9, "a"]. Mixing numbers and text in one list is an error: sort [1, "a"] stops with "can't sort string and integer together". A boolean sorts with a boolean (false first). import sort has key functions and other algorithms, such as case-insensitive text (see sort).
Plain <ident> is <expr> . (no at) is assignment/aliasing. An is line is a sentence, so it ends with a period like show and add; name = value is the same assignment without one.
insert and put both take a position from 0: insert 99 to nums at 1 . pushes the items from 1 along (the list gets longer); put 99 to nums at 1 . replaces the item at 1 (the length stays). put is a statement word only at the start of a line followed by a value; otherwise it's an ordinary name. As methods, both take the value first, then the position, as the sentences do: nums at insert[99, 1], nums at put[99, 1]; both give back the list. On a map, put and add take the key first, as a map is written: m at put["apples", 5] sets "apples" to 5, and m at add["apples", 3] adds 3 to it (a new key gets the value).
Setting an item or a key. The sentence is the same for every kind of value, and it names each part, so the two can't be swapped: put the value to the list or map, at the position or key. The method forms differ by kind, so learn the sentence first:
| Sentence | Method | |
|---|---|---|
| list | put 99 to nums at 1 . | nums at put[99, 1] (value, position) |
| list | insert 99 to nums at 1 . | nums at insert[99, 1] (value, position) |
| set | s at insert["x", 0] (value, position); s at get[0] reads by position | |
| map | put 5 to m at "apples" . | m at put["apples", 5] (key, value) |
| map | add 3 to m at "apples" . | m at add["apples", 3] (key, value) |
A map's put or add written in a list's order still runs as written, so m at put[1, "red"] adds the key 1. When the key is of a type none of the map's keys have and the value is already a key, or every entry is the other way round, Turtle warns once for that line and names the call to write: warning: put[1, "red"] looks swapped: a map's put takes the key first, so this adds the key 1. For the key "red", write put["red", 1] (line 3). help["list"] and help["map"] say the order too.
Lists, sets and maps hold other values by reference, so a list can be put inside itself (add x to x .). Showing, comparing, sorting, copying with copy[x, true], or using as a set item or map key walks the value to its end: one that holds itself, or one nested more than 100,000 levels deep, stops with an error ("this value is nested more than 100000 levels deep, or contains itself") that safe can handle, rather than running forever. A value always equals itself without that walk: x == x is true even after add x to x ., and so is it for a list holding nan compared with itself (two separate lists holding nan are not equal). JSON is written at most 10,000 levels deep, the depth load can read.
Every method, with examples
Each method on lists, sets and maps, with an example and the output it prints. Each example is a complete program. The list, set and map examples were run on Turtle v1.0.0. The string, number, matrix and date examples were run on v1.0.0 (source commit b7c0a9d). A method called after at changes the collection only when the entry says so. The errors at the end show what happens when a method is misused.
Lists
add adds a value at the end of the list (changes the list).
nums = list [4, 9]
nums at add[7]
show nums .
[ 4, 9, 7 ]
get gives back the item at an index. Positions start at 0.
nums = list [4, 9, 2]
show nums at get[1] .
9
put replaces the item at an index (changes the list). The value comes first, then the index.
nums = list [4, 9, 2]
nums at put[99, 1]
show nums .
[ 4, 99, 2 ]
insert inserts a value before an index, so the items after it move up (changes the list).
nums = list [4, 9, 2]
nums at insert[0, 1]
show nums .
[ 4, 0, 9, 2 ]
remove removes the first item equal to the value (changes the list). A value that is not there is not an error.
nums = list [4, 9, 2, 9]
nums at remove[9]
show nums .
nums at remove[42]
show nums .
[ 4, 2, 9 ]
[ 4, 2, 9 ]
pop removes an item and gives it back. With no index it takes the last item; with an index it takes that item.
nums = list [4, 9, 2]
show nums at pop .
show nums at pop[0] .
show nums .
2
4
[ 9 ]
slice gives a new list of the items from a start position up to, but not including, an end position. With no end, it goes to the end of the list. The original list is unchanged.
nums = list [4, 9, 2, 9]
show nums at slice[1, 3] .
show nums at slice[1] .
show nums .
[ 9, 2 ]
[ 9, 2, 9 ]
[ 4, 9, 2, 9 ]
contains gives true when the value is in the list. find is another name for contains.
nums = list [4, 9, 2]
show nums at contains[2] .
show nums at find[7] .
true
false
index gives the position of the first item equal to the value, or -1 when there is none.
nums = list [4, 9, 2, 9]
show nums at index[9] .
show nums at index[7] .
1
-1
count gives how many items are equal to the value.
nums = list [4, 9, 2, 9]
show nums at count[9] .
2
sort sorts the list in place (changes the list).
nums = list [4, 9, 2]
nums at sort
show nums .
[ 2, 4, 9 ]
reverse reverses the list in place (changes the list).
nums = list [4, 9, 2]
nums at reverse
show nums .
[ 2, 9, 4 ]
clear removes every item (changes the list).
nums = list [4, 9, 2]
nums at clear
show nums .
[]
len gives the number of items. length is another name for len.
nums = list [4, 9, 2]
show nums at len .
show nums at length .
3
3
isempty gives true when the list has no items.
nums = list []
show nums at isempty .
nums at add[1]
show nums at isempty .
true
false
tostring gives the list as text.
nums = list [4, 9]
text = nums at tostring
show "the list is {text}" .
the list is [ 4, 9 ]
Sets
add adds a value. A value already in the set is not added twice (changes the set).
colors = set ["red", "blue"]
colors at add["red"]
colors at add["green"]
show colors .
{ "red", "blue", "green" }
insert puts a value at a position in the set's order (changes the set). The value comes first, then the position. Sets have no order that means anything, so the book uses add instead.
colors = set ["red", "blue"]
colors at insert["green", 0]
show colors .
{ "green", "red", "blue" }
get gives the item at a position in the set's order. Positions start at 0. Sets have no order that means anything, so use get only to look at the items one by one.
colors = set ["red", "blue", "green"]
show colors at get[0] .
show colors at get[2] .
red
green
remove removes a value (changes the set). A value that is not there is not an error.
colors = set ["red", "blue"]
colors at remove["red"]
colors at remove["pink"]
show colors .
{ "blue" }
contains gives true when the value is in the set. find is another name for contains.
colors = set ["red", "blue"]
show colors at contains["red"] .
show colors at find["pink"] .
true
false
count gives 1 when the value is in the set, and 0 when it is not.
colors = set ["red", "blue"]
show colors at count["blue"] .
show colors at count["pink"] .
1
0
union gives a new set with the items of both sets. The original sets are unchanged.
a = set [1, 2]
b = set [2, 3]
show a at union[b] .
show a .
{ 1, 2, 3 }
{ 1, 2 }
intersection gives a new set with the items that are in both sets.
a = set [1, 2]
b = set [2, 3]
show a at intersection[b] .
{ 2 }
difference gives a new set with the items of this set that are not in the other set.
a = set [1, 2]
b = set [2, 3]
show a at difference[b] .
{ 1 }
subset gives true when every item of this set is in the other set.
a = set [1, 2]
b = set [1, 2, 3]
show a at subset[b] .
show b at subset[a] .
true
false
superset gives true when every item of the other set is in this set.
a = set [1, 2]
b = set [1, 2, 3]
show b at superset[a] .
show a at superset[b] .
true
false
pop removes an item and gives it back. It takes the item added most recently (changes the set).
colors = set ["red", "blue"]
show colors at pop .
show colors .
blue
{ "red" }
sort sorts the items (changes the set). The result is the same set, shown in sorted order.
nums = set [4, 8, 1]
nums at sort
show nums .
{ 1, 4, 8 }
clear removes every item (changes the set).
colors = set ["red", "blue"]
colors at clear
show colors .
{}
len gives the number of items. length is another name for len.
colors = set ["red", "blue"]
show colors at len .
2
isempty gives true when the set has no items.
colors = set []
show colors at isempty .
true
tostring gives the set as text.
colors = set ["red"]
text = colors at tostring
show "the set is {text}" .
the set is { "red" }
Maps
get gives the value for a key. A key that is not in the map is an error, so check with contains first when it may be missing.
ages = map ["Alice": 30, "Bob": 25]
show ages at get["Alice"] .
30
add adds to the value at a key (changes the map). For a number, the amount is added to the value, and a new key starts from the amount.
ages = map ["Alice": 30]
ages at add["Alice", 1]
ages at add["Cy", 5]
show ages .
{ "Alice": 31, "Cy": 5 }
put sets the value at a key, whether or not the key is there (changes the map).
ages = map ["Alice": 30]
ages at put["Alice", 31]
ages at put["Dee", 19]
show ages .
{ "Alice": 31, "Dee": 19 }
delete removes a key and its value (changes the map). A key that is not there is an error.
ages = map ["Alice": 30, "Bob": 25]
ages at delete["Alice"]
show ages .
{ "Bob": 25 }
contains gives true when the key is in the map.
ages = map ["Alice": 30]
show ages at contains["Alice"] .
show ages at contains["Zed"] .
true
false
getkeys gives a list of the keys, in the order they were added.
ages = map ["Bob": 25, "Alice": 30]
show ages at getkeys .
[ "Bob", "Alice" ]
getvalues gives a list of the values, in the same order as the keys.
ages = map ["Bob": 25, "Alice": 30]
show ages at getvalues .
[ 25, 30 ]
invert gives a new map with each key and value exchanged. The values become the keys. When two keys share a value, Turtle prints a warning and keeps only the last key.
ages = map ["Bob": 25, "Alice": 30]
show ages at invert .
show ages .
{ 25: "Bob", 30: "Alice" }
{ "Bob": 25, "Alice": 30 }
len gives the number of entries. length is another name for len.
ages = map ["Bob": 25, "Alice": 30]
show ages at len .
2
isempty gives true when the map has no entries.
ages = map []
show ages at isempty .
true
tostring gives the map as text.
ages = map ["Bob": 25]
text = ages at tostring
show "the map is {text}" .
the map is { "Bob": 25 }
Strings
upper gives back the text in capital letters.
show "turtle" at upper .
TURTLE
lower gives back the text in small letters.
show "TURTLE" at lower .
turtle
reverse gives back the text with its characters in reverse order.
show "turtle" at reverse .
eltrut
trim gives back the text with spaces removed from both ends.
show " hello " at trim .
hello
get gives back the character at an index. Positions start at 0; an index past the end is an error.
show "turtle" at get[1] .
u
slice gives back the part of the text from start up to, but not including, end.
show "turtle" at slice[0, 3] .
tur
split gives back a list of the pieces between each separator.
show "a,b,c" at split[","] .
[ "a", "b", "c" ]
contains gives back true if the text contains text.
show "turtle" at contains["urt"] .
true
indexof gives back the position of the first text in the string, or -1 if it is not there.
show "turtle" at indexof["rt"] .
show "turtle" at indexof["q"] .
2
-1
replace gives back the text with every old changed to new.
show "a-b-c" at replace["-", "+"] .
a+b+c
padleft gives back the text padded with spaces on the left to at least width characters.
show "7" at padleft[3] .
7
padright gives back the text padded with spaces on the right to at least width characters.
show "7" at padright[3] .
7
isnumber gives back true if the text is a number, such as "42" or "3.5".
show "42" at isnumber .
show "x3" at isnumber .
true
false
len gives back how many characters the text has.
show "turtle" at len .
6
isempty gives back true if the text has no characters.
show "" at isempty .
true
Numbers
fixed gives back the number as text with places digits after the point.
show 3.14159 at fixed[2] .
3.14
commas gives back a whole number as text with commas every three digits.
show 1234567 at commas .
1,234,567
commas[places] gives back a number as text with commas in the whole part and places digits after the point.
show 1234567.891 at commas[2] .
1,234,567.89
sqrt gives back the square root as a float. It needs import math. A negative number is a math error.
import math
show 16 at sqrt .
4.0
abs gives back the number without its sign. It needs import math.
import math
show -7 at abs .
7
round gives back the number rounded to the nearest whole number. It needs import math.
import math
show 2.6 at round .
3
floor gives back the largest whole number that is not more than the number. It needs import math.
import math
show 2.6 at floor .
2
ceil gives back the smallest whole number that is not less than the number. It needs import math.
import math
show 2.1 at ceil .
3
pow gives back the number raised to power. It needs import math.
import math
show 2 at pow[10] .
1024
random gives back a random whole number from 0 up to, but not including, the number. It needs import math. The example checks the range rather than printing the value, because the value changes each run.
import math
r = 10 at random
show r >= 0 && r < 10 .
true
Matrices
rows gives back how many rows the matrix has. It needs import linear.
import linear
m = matrix [1, 2; 3, 4]
show m at rows .
2
columns gives back how many columns the matrix has.
import linear
m = matrix [1, 2; 3, 4]
show m at columns .
2
shape gives back the rows and columns together, as a list [rows, columns].
import linear
m = matrix [1, 2; 3, 4]
show m at shape .
[ 2, 2 ]
get gives back the item at row r and column c. Both start at 0.
import linear
m = matrix [1, 2; 3, 4]
show m at get[0, 1] .
2
put puts value at row r and column c. It changes the matrix.
import linear
m = matrix [1, 2; 3, 4]
m at put[9, 0, 0]
show m .
[ 9 2 ]
[ 3 4 ]
row gives back row r as a matrix.
import linear
m = matrix [1, 2; 3, 4]
show m at row[1] .
[ 3, 4 ]
column gives back column c as a matrix.
import linear
m = matrix [1, 2; 3, 4]
show m at column[0] .
[ 1, 3 ]
flatten gives back all the items in one row.
import linear
m = matrix [1, 2; 3, 4]
show m at flatten .
[ 1 2 3 4 ]
reshape gives back the same items arranged in rows rows and columns columns. The item count must match.
import linear
m = matrix [1, 2; 3, 4]
show m at reshape[1, 4] .
[ 1 2 3 4 ]
isempty gives back true if the matrix has no items.
import linear
m = matrix [1, 2; 3, 4]
show m at isempty .
false
tostring gives back the matrix as text.
import linear
m = matrix [1, 2; 3, 4]
show m at tostring .
[ 1 2 ]
[ 3 4 ]
Dates
tostring gives back the date as text, as show writes it. No import is needed.
import time
d = make_date[2026, 10, 10]
show d at tostring .
2026-10-10 00:00:00
Errors and limits
Each of these stops the program with an error. The message names the problem, and the line shows where it happened.
A list position past the end is an error.
nums = list [4]
show nums at get[5] .
turtle: line 2: index 5 out of range for list (length 1)
2 | show nums at get[5] .
pop on an empty list is an error.
nums = list []
show nums at pop .
turtle: line 2: 'pop' called on an empty list
2 | show nums at pop .
A map key that is not there is an error for get and for delete.
ages = map ["Bob": 25]
show ages at get["Zed"] .
turtle: line 2: key "Zed" not found in map
2 | show ages at get["Zed"] .
put is not a method of a set.
colors = set ["red"]
colors at put["blue", 0]
turtle: line 2: unknown set method "put"
2 | colors at put["blue", 0]
clear is not a method of a map.
ages = map ["Bob": 25]
ages at clear
turtle: line 2: unknown map method "clear"
2 | ages at clear
A set position past the end is an error.
colors = set ["red", "blue"]
show colors at get[5] .
turtle: line 2: index 5 out of range for set (length 2)
2 | show colors at get[5] .
When two keys in a map share a value, invert warns and keeps only the last key.
ages = map ["Bob": 25, "Ann": 25]
show ages at invert .
warning: 25 is the value of both "Bob" and "Ann", so the inverted map keeps only "Ann" (line 2)
{ 25: "Ann" }
Files
[read] <path> to <ident> [end]
[write] <path>
<string-or-ident>
...
[end]
[append] <path>
<string-or-ident>
...
[end]
[directory] <path> to <ident> [end]
<path> is any of:
- an expression that builds it:
folder + "/" + name + ".txt",names at get[0],path of doc,file_for[id](a word or string followed by+,[,atorof) - a quoted string, with values inside it:
"{folder}/{name}.txt" - a variable:
[read] name to linesuses the variablenameif there is one, else the file calledname - a bareword like
file.txtordata/in-1.csv, the file of that name
[read] folder + "/" + day + ".csv" to rows [end]
[write] receipts at get[0]
"paid"
[end]
Relative paths resolve from the folder turtle was run in (see the system docs). [write]/[append] body lines are one item each: a quoted string is written verbatim, a bare identifier is replaced with that variable's current value; items are newline-joined.
The program writes notes.txt in the folder it is run from, then reads it back.
Example.
[write] notes.txt
"first line"
"second line"
[end]
[append] notes.txt
"third line"
[end]
[read] notes.txt to lines [end]
show length of lines .
show lines at get[2] .
3
third line
Modules
import <name> // everything the module exports
import <name> [<f>, <g>, ...] // only the listed names
import <name> as <alias> // the module is called <alias> in this file
import <name> [<f> as <g>, ...] // the listed name <f> is <g> in this file
An alias lets a file use a name that another import, or its own theory, already has. import data as d makes d sum[nums] and d mean[nums]; import data [mean as average] makes average[nums], and mean isn't available under its own name in that file. A file can't import the same module under two names, and two modules can't share an alias.
<name> is a builtin module (math, time, data, strings, system, json, http, sql, sort, search, random, pattern, crypt, schedule, config, server, log, test, linear; see the library docs) or a file <name>.turtle, resolved relative to the current script's directory. A module in a subfolder is written with /: import lib/utils reads lib/utils.turtle, and its qualified name is the last part, utils half[4]. Because builtin names win, don't name your own module file after one (math.turtle, json.turtle, ...); import lib/json is an error for the same reason.
What a module exports. A .turtle module exports its top-level functions, and only those. It runs once, in its own global scope, the first time any file imports it; later imports reuse it. Its top-level variables stay private to it, although its own functions can read them. A function you import keeps calling the module's other functions, even ones you didn't import, and those never leak into your program. A module's own imports aren't passed on to the files that import it.
Private functions: ~. A function whose name starts with ~ is private to its file: its own code uses it like any other, and files that import the module can't, by any route (~limit[...], shop ~limit[...] and import shop [~limit] all say it's private). ~limit and limit are two different names, so a public function can check its values and hand the work to a private one:
// limit keeps n between low and high.
def limit[n, low, high]
if ] low > high [
fail "limit: low is above high"
if [end]
return ~limit[n, low, high]
def [end]
// ~limit does the work, for values already checked.
def ~limit[n, low, high]
return min of list [max of list [n, low], high]
def [end]
Only a function's name can start with ~. Variables are private to their file already, and an assembled type stays public, since the values a module gives back are its users' to work with. A test file run by turtle test can use the private functions of the modules it imports, to test them (see testing.md). turtle doc on the file documents its public functions and lists the private ones at the end.
Plain and qualified names. Imported functions are called by their plain name: t = now[]. You can always name the module explicitly by writing it in front, separated by a space: t = time now[]. Without brackets, mylib binary is the function itself as a value, the same as a plain function name.
Clashes. Importing two modules that export the same function name is fine. Calling that name unqualified is a fatal error that asks you to choose: "now" is provided by more than one import (time, mylib) — say which one, e.g. time now[...]. Every other name from those modules keeps working unqualified. Your own top-level def always wins over an imported function with the same name, and the module's version stays reachable qualified (time now[]).
Import lists. import time [sleep, now] makes only the listed names available, plain or qualified. Anything else from that module is a fatal error naming the list to add it to. A listed name the module doesn't export is a fatal error at the import line. import m [] is a parse error. Importing the same module again merges: lists accumulate, and a full import makes everything available.
Settings in the import line. A name = value inside the brackets sets a variable of the importing file, once the import has run, exactly as a line name = value after the import would:
import data [tablerows = 50] // everything, with 50 rows shown
import data [tablerows = 50, process] // only process, with 50 rows shown
import log [loglevel = "debug"]
import random [seed = 7]
Plain names still choose what is imported. With settings and no plain names, the whole module is imported. The value is any expression, evaluated in the importing file, and the setting can be changed on a later line as usual. A setting replaces the library's default, and a missing value is a parse error.
Imports apply per file: the main program and each module only see what they themselves imported. A circular import (a imports b imports a) is a fatal error that shows the chain.
Examples, with what each shows:
// shop.turtle, next to the program
taxrate = 0.08 // private to shop
def withtax[amount]
return amount + amount * taxrate
def [end]
def now[]
return "shop's now"
def [end]
Illustrative. This example needs a module file (shop.turtle) that is not in the repository, so it is shown for reading and is not run as a test.
import math // a built-in library
import time [now] // only now
import data
import shop // shop.turtle
import lib/money // lib/money.turtle, named money
show withtax[100] . // 108.0: the plain name
show shop withtax[50] . // 54.0: named with its module
show money half[9] . // 4.5
f = shop withtax // the function itself, as a value
show f[10] . // 10.8
show nums sum . // an imported function as a sentence: sum[nums]
show time now[], shop now[] . // both export now: name the module
x = now[] // error: "now" is provided by more than one import (time, shop)
sleep[0] // error: "sleep" isn't imported — add it to "import time [...]"
show taxrate . // error: undefined variable "taxrate"
Without import data, sum[nums] is an error that names the import: "sum" needs "import data" first. Some imports also turn on words of the language for that file (random, check, log, matrix): see Keywords.
Builtin modules.
import mathunlocks number methods:sqrt,abs,round,floor,ceil,pow,random(see themathdocs). Methods are called on a value (r is 16 at sqrt .), so they never clash and are never qualified; an import list still limits which ones you can use (import math [sqrt]).import timeprovides two builtin functions:now[](milliseconds since the Unix epoch, as an Integer) andsleep[<amount> [, <unit>]](pauses;<unit>is"seconds", the default, or"ms"; returnsnone). Builtin functions can be called but not used as values.import systemprovidesargs[](the command-line arguments after the script path),exists/isfile/isfolder,contents[path],exit[code],env[name]andscriptfolder[](see thesystemdocs).import stringsprovidesfind,substring,isinstringandjoin(see thestringsdocs).import sqlprovidessql_open,sql_create,sql_query,sql_run,sql_tables,sql_close, and moves files in and out of a database withsql_save,sql_load,sql_update,sql_delete,sql_upsert(see thesqldocs).import dataprovidesprocess,keep, andcopy, which apply a function across a list, set, or map,table, which lays rows out as a text table, andtable_write/table_read, which save and read.csv,.tsv,.txtand.jsontable files (see thedatadocs). They're ordinary functions, usually called sentence-style:nums process x give x + 1 .,show table[rows] .It also has the statistics:mean,median,mode,variance,stdev,pvariance,pstdev,percentile,covariance,correlation,zscores,describe(see thedatadocs).import linearadds thematrixvalue, writtenmatrix [1, 2; 3, 4](rows end at;or at the end of a line), its operators (*of two matrices is the matrix product), and functions such assolve,inverse,determinant,eigenandsvd(see thelineardocs).matrixis a word of the language only in a file that importslinear; elsewhere it's an ordinary name, and in such a file it can't name a variable or function.import randommakes random values of any shape, written as a sentence:random list of 5 integers from 0 to 9,random Order [string, integer]; pluspick,shuffle,sample,chanceand theseedvariable (see therandomdocs).randomis a sentence word only in a file that imports it.import sortprovidesmin_sort/max_sort(order by a function, field, position or several, and take the"first"or a count),is_sorted,reverse_list, and the classic sorting algorithms; andimport searchprovidesfind_first,find_all,find_key, ... and linear, binary and other searches (see thesortdocs).import sortnames the library;sort nums .on its own is still the in-place sort statement.
Using a math method or now/sleep without the matching import is a fatal error naming exactly which import is missing.
Illustrative. This example needs files that the example does not create, so it is shown for reading and is not run as a test.
import time
import mylib [binary, now]
r = binary[5] // only mylib has binary
t = time now[] // both have now: name the module
m = mylib now[]
sleep[0.5] // only time has sleep
The module is the file lib/utils.turtle, next to the program. Its functions are called with the module's name in front: utils half[4].
Example.
import lib/utils
show utils half[4] .
2.0
Database servers: queryall
queryall runs several queries on a PostgreSQL or MySQL server at once, each over its own connection. This example creates a table, adds three rows, and runs two queries in one call. Put your own server address in sql_open; this one is a local PostgreSQL server.
Example.
import sql
import schedule
db = sql_open["postgres://postgres:pw@127.0.0.1:55432/shop?sslmode=disable"]
sql_run[db, "DROP TABLE IF EXISTS books"]
sql_run[db, "CREATE TABLE books (title TEXT, price INTEGER)"]
sql_run[db, "INSERT INTO books VALUES ('Dune', 900), ('Emma', 1200), ('Ulysses', 800)"]
r = queryall[db, list ["SELECT count(*) AS n FROM books", list ["SELECT * FROM books WHERE price < ?", list [1000]]]]
show r .
sql_close[db]
[ [ { "n": 3 } ], [ { "title": "Dune", "price": 900 }, { "title": "Ulysses", "price": 800 } ] ]
The result is one list per query: the count, then the rows under 1000.
Shell escape
sys <rest of line>
sys must be the first word of the statement. Everything after it, verbatim to end of line, runs through a shell (sh, or cmd on Windows) with inherited stdin/stdout/stderr, in the folder turtle was run in (where file paths resolve too).
sys runs a command in the shell and waits for it to finish.
Example.
sys echo hello from the shell
hello from the shell
Logging: log
In a file with import log (settings and examples: the log docs):
log [debug | info | warn | error] <expr> {, <expr>} .
The values are joined as show joins them; a map among them adds key=value fields. Without a level word it's info. log begins a statement only when a value or a level word follows it, so log = 5 still assigns.
Each line has the time it was written, so the times here will differ on your run.
Example.
import log
log info "starting" .
log warn "disk at ", 91, "%" .
2026-11-19 01:11:49 INFO starting
2026-11-19 01:11:49 WARN disk at 91%
Tests: check, verify, validate, turtle test
In a file with import test, three more statements (full guide: testing.md):
check <expr> . // true or false; == explains a difference
check <expr> is [not] <kind> . // integer float number string boolean list set map date none function empty, or an assembled type
check <expr> is [not] close to <expr> [within <expr>] .
check <expr> fails [<kind>, ...] . // the brackets are optional: any error
verify <expr> <how many> <rule> .
validate <call> [to <name>] [with <name> as <kind>, ...] that <rule> .
validate <call> [to <name>] [with <name> as <kind>, ...] matches <call> .
<how many>iseach,any,not,at least N,at most Norexactly N, optionally followed bypair(neighbors two at a time).<rule>is a function giving true or false (x give x > 0, or a function's name).validate's<kind>uses the random library's words (list of integer,Order [string, integer]); its rule isthatfollowed by a true/false expression or a verify-style rule (that result each x give ...), ormatchesanother call. Withoutwith, it learns the kinds from the same test's checks on that function. The sentence can go over several lines; it ends at its period.- A failure is an error of kind
test. check,verifyandvalidateare statement words only afterimport test; elsewhere they're ordinary names. In such a file a function can't be named one of them.import testalso makes the variablessuite,benchmark,runs,benchtime,casesandseed.
turtle test [file.turtle | folder ...] runs every top-level test_ function (no arguments) in every test_*.turtle file, after the file's own top-level code, and exits with 1 if any failed.
The second check is false, so the program stops with a test error that says what was expected.
Example.
import test
def sum_two[a, b]
return a + b
def [end]
check sum_two[2, 3] == 5 .
check sum_two[2, 3] == 6 .
turtle: line 6: failed: check sum_two[2, 3] == 6 .
got 5, want 6 (1 less)
6 | check sum_two[2, 3] == 6 .
Example. turtle test runs each test_ function in the test_*.turtle files of a folder:
$ turtle test tests
tests/test_math.turtle
PASS test_sum 23.6µs 99.4 KB
ok: 1 passed, 0 failed (1 file, 156.5µs)
Watching it run: turtle trace
turtle trace script.turtle [args] runs the program as usual and, on standard error, shows each line as it runs. A line that sets a variable shows the value it got:
line 1 nums = list [5, 7] nums = [ 5, 7 ]
line 2 total = 0 total = 0
line 3 [loop][x in nums]
line 4 total = total + x total = 5
line 4 total = total + x total = 12
line 6 d = double[total]
line 9 return n * 2
line 6 ... d = 24
When a line calls a function, the function's lines come next, and the value follows on a ... line. Lines of an imported file are named with the file (utils.turtle:4). def lines are left out: functions are defined before the file runs. The program's own output stays on standard output, so turtle trace report.turtle 2> trace.txt keeps the two apart.
Example. Run the program with trace and read the lines it shows on standard error:
$ turtle trace main.turtle
12
line 1 nums = list [5, 7] nums = [ 5, 7 ]
line 2 total = 0 total = 0
line 3 [loop][x in nums]
pass 1: x = 5
line 4 total = total + x total = 5
pass 2: x = 7
line 4 total = total + x total = 12
line 6 show total .
Stepping through it: turtle debug
turtle debug script.turtle [args] runs the program a line at a time. It stops before the first line, shows the line it's on, and waits:
→ line 9 r = n * 2
(debug) p n
12
(debug) v
here:
n = 12
globals:
nums = [ 5, 7 ]
total = 12
| Command | Does |
|---|---|
Enter or s | step: run this line, stop at the next (going into functions) |
n | next: run this line and any functions it calls |
o | out: run to the end of this function |
c | continue to the next breakpoint, or the end |
b 12 | stop at line 12 (b utils.turtle:4 in an imported file); b alone lists them |
d 12 | remove that breakpoint |
p <value> | show a value: p total, p nums at len |
v | the variables here, then the globals |
w | where: the functions being run, outermost first |
l | the lines around this one |
q | quit the program |
h | the commands |
Anything else is run as Turtle, right there: total shows its value, n = 100 changes n before the line runs, show nums . shows. An error in what you type is shown and the program carries on. The debugger writes to standard error and reads standard input, like the program's ? prompts. If the input ends, the program runs to the end.
Example. Step four lines, look at total, then run to the end. The typed commands are the ones after (debug):
$ turtle debug main.turtle
12
turtle debug: stopped before the first line. Enter steps; h shows the commands.
→ line 1 nums = list [5, 7]
(debug) → line 2 total = 0
(debug) → line 3 [loop][x in nums]
(debug) → line 4 total = total + x
(debug) → line 4 total = total + x
(debug) 5
(debug)
Layout: turtle fmt
turtle fmt lays .turtle files out the standard way: each block's lines four spaces in from the line that opens it (def, if ] ... [, [loop][...], safe, give, [write]), else and handle lined up with their block, that one step in under its validate, no spaces at line ends, at most two blank lines in a row, and one newline at the end.
turtle fmt # every .turtle file here and in the folders below
turtle fmt report.turtle lib # these files and folders
turtle fmt --check # change nothing; list what needs it (exit 1 if any)
It only changes the space at the start and end of lines, never what's on them (in Turtle a space can matter: nums get -1 isn't a - 1). Lines inside a ` raw string or a //* *//` comment are left as they are. A file that doesn't parse is reported and left alone. In VS Code, Format Document (Shift-Alt-F) does the same.
Example. fmt --check lists the files that need laying out, and fmt rewrites them. Here the if block is not indented:
$ turtle fmt --check ugly.turtle
ugly.turtle needs formatting
$ turtle fmt ugly.turtle
After fmt the file reads:
if ] x > 1 [
show "big" .
if [end]
Sharing a program: turtle build
turtle build report.turtle // makes report (report.exe on Windows)
turtle build report.turtle -o tool // makes tool
turtle build makes one program file that runs without Turtle installed: a copy of turtle with the script and every .turtle file it imports (however deep) packed into it. Run it like any program; every argument goes to the script (args[]):
./report 2026 "north region"
- For the system it's built on. turtle on a Mac makes a Mac program, on Windows a
.exe, on Linux a Linux program. To share a tool with Windows users, runturtle buildon Windows. - Data files aren't packed. CSV files, settings and the like are read as with turtle: file paths from the folder the program is run in.
scriptfolder[]is the program's own folder. - Libraries are built in.
import json,import sqland the rest are part of every program; only your own.turtlefiles are packed. - Size. A program is about the size of turtle (10 to 15 MB): turtle is inside it.
- Mistakes are found first. A script that doesn't parse, or imports a file that isn't there, isn't built.
- macOS. A program made on your Mac runs on it. Copied to another Mac by download, macOS may say it's damaged (it isn't signed by Apple);
xattr -d com.apple.quarantine reportlets it run. - Windows. A program can't be rebuilt while it's running: close it first. Downloaded on another PC, Windows may say it "protected your PC" (it isn't signed); More info, then Run anyway, lets it run.
Example. build makes one program file that runs without Turtle installed. Then run the file:
$ turtle build main.turtle -o app
built app (main.turtle, darwin/arm64)
$ ./app
12
Documentation: turtle doc
turtle doc shows what every library function takes and gives back:
turtle doc # every library and its functions
turtle doc sql # one library, every function in full
turtle doc sql_update # one function
turtle doc lib/shop.turtle # the functions of your own file
Document your own functions with comments directly above the def (or assemble), or first in the function's body, either kind: // lines or a //* ... *// block. The // lines at the very top of a file describe the file. Say what each parameter is and what the function gives back:
// shop.turtle: helpers for the bookshop database.
// add_tax adds rate percent to an amount, rounded to the cent.
// cents is a whole number of cents; rate is a percent, like 8.
// Gives back the new amount in cents.
def add_tax[cents, rate]
...
def [end]
turtle doc shop.turtle then lists add_tax[cents, rate] with those lines. A function without them is listed as having no description. The same comment can go inside, as the first thing in the body:
def add_tax[cents, rate]
//* adds rate percent to an amount, rounded to the cent.
Gives back the new amount in cents. *//
...
def [end]
A comment after the first line of code is an ordinary comment, not the description. Comments in both places are shown together, the one above first. Editors show the description on hover (see editors.md).
Example. doc shows the documentation for a library, a function or a file:
$ turtle doc reshape
reshape[m, rows, columns] (import linear)
The same numbers, in the same order, as a rows x columns matrix. m is
unchanged. rows times columns must be how many numbers m has, or it's a
linear error. Method: m at reshape[rows, columns]. Sentence form:
m reshape rows, columns.
Example:
m = matrix [1, 2, 3; 4, 5, 6]
r = reshape[m, 3, 2] // [ 1 2 ]
// [ 3 4 ]
// [ 5 6 ]Top
Turtle