Standard library reference

Every function Baa ships with. Module names are sheep-themed; the functions inside them are not: an API you have to remember at 2am is no place for a joke.

  • The prelude, available without an import
  • Methods, available on values themselves
  • wool: Text: formatting, casing, wrapping, bytes.
  • flock: Collections: grouping, chunking, zipping, building maps.
  • ram: Arithmetic: rounding, integer division, statistics, constants.
  • meadow: Time and chance: clocks, calendars, seeded randomness.
  • pasture: Files and paths: reading, writing, listing, joining.
  • shepherd: The outside world: arguments, environment, stdin, subprocesses.
  • lamb: Data: JSON encoding and decoding.
  • gate: The web: reading a request and writing a reply, over CGI.
  • barn: Native windows: controls, layout and events. Needs the native runtime.

The prelude#

These names are in scope in every file, with no import. A local declaration may shadow any of them.

FunctionArgumentsDescription
len1Length of a string, array, map or range.
type_of1Type name: "nil", "bool", "number", "string", "array", "map", "range", "function" or "module".
to_string1Text form of any value.
inspect1Developer-facing form of any value, with quoted strings.
to_number1Parse a value as a number, or nil when it is not numeric.
clone1Deep copy of an array or map. Other values are returned unchanged.
assert1-2Fail the program when a condition is not truthy.
assert_eq2-3Fail unless two values are equal, showing both when they are not.
panic1Stop the program immediately with a message.
exit0-1Exit the program with a status code (default 0).

Methods#

Methods are looked up on the value itself and are ordinary first-class functions: const shout = "baa".upper then shout() works.

On every value#

MethodArgumentsDescription
to_string0Text form of this value.
inspect0Developer-facing form, with quotes.
type_of0Name of this value's type.

On string#

MethodArgumentsDescription
length0Number of characters.
is_empty0True when the string has no characters.
upper0Uppercase copy.
lower0Lowercase copy.
trim0Copy without leading or trailing whitespace.
trim_start0Copy without leading whitespace.
trim_end0Copy without trailing whitespace.
contains1True when the string contains a substring.
starts_with1True when the string starts with a prefix.
ends_with1True when the string ends with a suffix.
index_of1First index of a substring, or -1.
split0-1Split into an array on a separator.
lines0Split into an array of lines.
chars0Array of single-character strings.
replace2Replace the first occurrence.
replace_all2Replace every occurrence.
slice1-2Substring from start (inclusive) to end (exclusive).
repeat1Repeat the string n times.
pad_start1-2Pad on the left to a target width.
pad_end1-2Pad on the right to a target width.
reverse0Reversed copy.
to_number0Parse as a number, or nil when it isn't one.

On array#

MethodArgumentsDescription
length0Number of items.
is_empty0True when there are no items.
push1+Append items; returns the array.
pop0Remove and return the last item, or nil.
shift0Remove and return the first item, or nil.
unshift1+Insert items at the front.
insert2Insert a value at an index.
remove1Remove the item at an index and return it.
clear0Remove every item.
contains1True when a value is present.
index_of1First index of a value, or -1.
first0First item, or nil.
last0Last item, or nil.
slice1-2Sub-array from start (inclusive) to end (exclusive).
concat1New array with another array appended.
join0-1Join items into a string.
reverse0Reversed copy.
map1New array with fn applied to each item.
filter1New array of items where fn is truthy.
reduce2Fold the array into a single value.
for_each1Call fn with each item.
find1First item where fn is truthy, or nil.
any1True when fn is truthy for any item.
all1True when fn is truthy for every item.
count0-1Count items, optionally matching fn.
sort0-1Sorted copy; pass fn(a, b) for a custom order.
unique0Copy with duplicates removed, keeping first occurrences.
flatten0Concatenate nested arrays one level deep.
sum0Add every item; all items must be numbers.

On map#

MethodArgumentsDescription
length0Number of entries.
is_empty0True when there are no entries.
get1-2Value for a key, or a fallback (default nil).
expect1Value for a key; fails when the key is missing.
set2Insert or replace a key; returns the map.
has1True when the key is present.
remove1Remove a key; returns the removed value or nil.
clear0Remove every entry.
keys0Array of keys, in insertion order.
values0Array of values, in insertion order.
entries0Array of [key, value] pairs.
merge1New map with another map's entries layered on top.
for_each1Call fn with each key and value.

On range#

MethodArgumentsDescription
length0How many values the range yields.
start0First value.
end0Bound value.
is_empty0True when the range yields nothing.
contains1True when a number falls inside the range.
to_array0Materialise the range as an array.

On number#

MethodArgumentsDescription
abs0Absolute value.
floor0Round down.
ceil0Round up.
round0Round to the nearest whole number.
is_whole0True when the number has no fractional part.
to_fixed1Text with a fixed number of decimal places.
clamp2Constrain between a low and high bound.

wool#

Text: formatting, casing, wrapping, bytes.

baa
import wool
FunctionArgumentsDescription
wool.join1–2Join an array of values into a string.
wool.concat0+Concatenate every argument as text.
wool.format1+Fill %s placeholders in order: wool.format("%s of %s", 3, 10). %% is a literal percent.
wool.repeat2Repeat a string n times.
wool.title_case1Capitalise the first letter of each word.
wool.snake_case1Convert text to snake_case.
wool.camel_case1Convert text to camelCase.
wool.kebab_case1Convert text to kebab-case.
wool.wrap2Wrap text to a maximum line width, breaking on spaces.
wool.center2–3Centre text within a width.
wool.escape_html1Escape text so it is safe inside HTML or an attribute.
wool.safe_url1A URL if its scheme is safe to link to, otherwise nil.
wool.percent_encode1Percent-encode text for use in a URL.
wool.percent_decode1Decode percent-encoded text, or nil when it is malformed.
wool.matches2–3True when a pattern matches anywhere in the text.
wool.find2–3First match as a map of match, start, end and groups, or nil.
wool.find_all2–3Every non-overlapping match, as an array of maps.
wool.substitute3–4Replace every match. $1 in the replacement is a group.
wool.split_on2–3Split text on every match of a pattern.
wool.is_blank1True when a string is empty or only whitespace.
wool.to_bytes1UTF-8 byte values of a string.
wool.from_bytes1Build a string from an array of UTF-8 byte values.
wool.inspect1Developer-facing text for any value.

flock#

Collections: grouping, chunking, zipping, building maps.

baa
import flock
FunctionArgumentsDescription
flock.of0+Build an array from the arguments.
flock.repeat2An array with the same value repeated n times.
flock.zip2Pair up two arrays, stopping at the shorter one.
flock.chunk2Split an array into chunks of a fixed size.
flock.group_by2Group items into a map keyed by fn(item).
flock.partition2Split into [matching, rest] using a predicate.
flock.sort_by2Sorted copy, ordered by the key fn(item) returns.
flock.min_by2Item with the smallest fn(item), or nil when empty.
flock.max_by2Item with the largest fn(item), or nil when empty.
flock.to_map1Build a map from an array of [key, value] pairs.
flock.from_keys2Build a map giving every key the same value.
flock.invert1Swap a map's keys and values.
flock.range1–3An array of numbers: range(end), range(start, end[, step]).
flock.to_array1Turn a range, string or map into an array.
flock.union2Everything in either array, first-seen order, no repeats.
flock.intersect2Everything in both arrays, in the first array's order.
flock.difference2Everything in the first array and not the second.
flock.is_subset2True when every item of the first array is in the second.

ram#

Arithmetic: rounding, integer division, statistics, constants.

baa
import ram
ConstantValue
ram.PI3.141592653589793
ram.E2.718281828459045
ram.TAU6.283185307179586
ram.INFinf
ram.NANnan
ram.EPSILON2.220446049250313e-16
ram.MAX_SAFE_WHOLE9007199254740991
FunctionArgumentsDescription
ram.abs1Absolute value.
ram.sign1-1, 0 or 1.
ram.floor1Round down.
ram.ceil1Round up.
ram.trunc1Drop the fractional part.
ram.round1–2Round to the nearest whole number, or to n decimal places.
ram.sqrt1Square root.
ram.pow2Raise to a power.
ram.exp1e raised to a power.
ram.log1–2Natural logarithm, or logarithm in a given base.
ram.sin1Sine, in radians.
ram.cos1Cosine, in radians.
ram.tan1Tangent, in radians.
ram.atan22Angle of the vector (x, y), in radians.
ram.hypot2Length of the vector (x, y).
ram.min1+Smallest of the arguments.
ram.max1+Largest of the arguments.
ram.clamp3Constrain a value between low and high.
ram.lerp3Linear interpolation between a and b.
ram.idiv2Integer division, rounding toward negative infinity.
ram.modulo2Remainder that always takes the sign of the divisor.
ram.gcd2Greatest common divisor of two whole numbers.
ram.is_nan1True when the value is not a number.
ram.is_finite1True when the value is a finite number.
ram.is_whole1True when the value is a whole number.
ram.sum1Add every number in an array.
ram.mean1Arithmetic mean of an array, or nil when empty.
ram.median1Median of an array, or nil when empty.
ram.to_binary1Binary text for a whole number.
ram.to_hex1Hexadecimal text for a whole number.
ram.parse1–2Parse text as a number in a given base (default 10).

meadow#

Time and chance: clocks, calendars, seeded randomness.

baa
import meadow
FunctionArgumentsDescription
meadow.now0Milliseconds since 1970-01-01 UTC.
meadow.clock0High-resolution milliseconds, for measuring durations.
meadow.parts0–2Break a timestamp into calendar parts (UTC, or at an offset).
meadow.format1–2Format a timestamp as YYYY-MM-DD or with a pattern.
meadow.iso0–2ISO-8601 text for a timestamp (default: now, UTC).
meadow.duration1Break a length of time in milliseconds into parts.
meadow.format_duration1A length of time as 1d 2h 3m 4s.
meadow.parse_iso1Parse ISO-8601 text into a timestamp, or nil.
meadow.random0A random number in [0, 1).
meadow.random_int2A random whole number between low and high, inclusive.
meadow.pick1A random item from an array or range, or nil when empty.
meadow.shuffle1A shuffled copy of an array.
meadow.sample2n random items from an array, without repeats.

Time zones. Baa carries no zone database, so there is nothing to name a zone with. What it has instead is fixed offsets: meadow.parts(millis, 60) and meadow.iso(millis, 60) read an instant as a clock one hour ahead of UTC would, and the ISO text ends in +01:00 rather than Z. Offsets are whole minutes between -720 and +840, which is the range zones actually use; anything else is BAA311.

This is deliberately not Europe/London: an offset is a fact about an instant, while a zone name is a rule that changes twice a year and needs a database that ships updates. Guessing would be worse than not offering it.

Durations. meadow.duration(millis) breaks a length of time into days, hours, minutes, seconds and milliseconds, with negative saying which way it runs. meadow.format_duration(millis) writes the same thing as 1d 2h 3m 4s, leaving out the units above the largest one that applies.

pasture#

Files and paths: reading, writing, listing, joining.

baa
import pasture
ConstantValue
pasture.SEPARATORthe host path separator: \ on Windows, / elsewhere
FunctionArgumentsDescription
pasture.read1Read a whole text file as a string.
pasture.read_lines1Read a text file and split it into lines.
pasture.write2Write text to a file, replacing anything already there.
pasture.append2Append text to a file, creating it when missing.
pasture.write_lines2Write an array of lines to a file.
pasture.exists1True when a file or directory exists.
pasture.list1Names inside a directory.
pasture.make_dir1Create a directory, including any missing parents.
pasture.info1Size, kind and modification time of a path, or nil.
pasture.join1+Join path segments with the platform separator.
pasture.resolve1+Turn path segments into one absolute path.
pasture.dir_name1The directory part of a path.
pasture.base_name1–2The final component of a path, optionally without a suffix.
pasture.extension1The file extension, including the dot.
pasture.normalise1Collapse . and .. segments.
pasture.relative_to2The path from one location to another.
pasture.is_absolute1True when a path is absolute.
pasture.cwd0The current working directory.
pasture.walk1–2Every file under a directory, recursively, sorted.
pasture.glob2Files under a directory whose path matches a glob pattern.
pasture.matches2True when a path matches a glob pattern.

Glob patterns. pasture.glob and pasture.matches understand three things:

PatternMatches
?one character, never a separator
*any run of characters, never crossing a separator
**any run of characters, separators included

Nothing else is special: [, { and the rest match themselves. A pattern that means one thing in bash and another in zsh is worse than one that means itself, and the small set covers what a build script asks for.

Matching is over whole paths, not suffixes, and pasture.glob matches against paths relative to the directory it was given: *.baa matches main.baa and not src/main.baa, and **/*.baa matches both. Either separator works in a pattern, so one pattern reads the same on Windows and elsewhere.

Walking. pasture.walk returns files and not directories, depth-first through names sorted at each level, and stops at 64 levels deep so that a link pointing back up its own tree cannot run forever.

shepherd#

The outside world: arguments, environment, stdin, subprocesses.

baa
import shepherd
ConstantValue
shepherd.PLATFORMthe host platform: win32, linux, darwin, ...
shepherd.ARCHthe host architecture: x64, arm64, ...
FunctionArgumentsDescription
shepherd.args0Arguments passed to the Baa program after --.
shepherd.env1–2An environment variable, or a fallback when it is unset.
shepherd.env_all0Every environment variable as a map.
shepherd.write1+Write to stdout without a trailing newline.
shepherd.write_error1+Write to stderr without a trailing newline.
shepherd.input0–1Read one line from stdin, or nil at end of input.
shepherd.read_all0Read all of stdin as a single string.
shepherd.run1–3Run a program with an explicit argument array. Never uses a shell.
shepherd.exit0–1Exit with a status code (default 0).

lamb#

Data: JSON encoding and decoding.

baa
import lamb
FunctionArgumentsDescription
lamb.encode1–2JSON text for a value; pass an indent for pretty output.
lamb.decode1Parse JSON text into Baa values.
lamb.try_decode1–2Parse JSON text, or return a fallback (default nil).
lamb.is_valid1True when a string parses as JSON.

gate#

The web: reading a request and writing a reply, over CGI.

baa
import gate
FunctionArgumentsDescription
gate.method0The request method, uppercase. Defaults to GET.
gate.path0The path below the script, or "/".
gate.query0The query string parsed into a map.
gate.query_string0The raw, undecoded query string.
gate.body0The request body as text.
gate.form0A urlencoded request body parsed into a map.
gate.header1–2A request header, or a fallback when it is absent.
gate.headers0Every request header as a map, in Header-Case.
gate.cookies0The Cookie header parsed into a map.
gate.status1Set the status code. Must come before the reply starts.
gate.set_header2Set a response header. Must come before the reply starts.
gate.text1Reply with plain text.
gate.html1Reply with HTML, exactly as given. Escape values yourself.
gate.fill1+Reply with HTML, escaping each value put into a %s. The safe way to build a page.
gate.json1Reply with a value encoded as JSON.
gate.redirect1–2Reply with a redirect (303 by default).
gate.escape1Escape a value for HTML. Same as wool.escape_html.
gate.safe_url1–2A URL if its scheme is safe to link to, else a fallback (default "#").
gate.format1+Build HTML, escaping each value put into a %s, without sending it.

barn#

Native windows: controls, layout and events. Needs the native runtime.

baa
import barn
FunctionArgumentsDescription
barn.window0–1Create a window. Options: title, width, height, padding, spacing.
barn.row1–2A container that lays its children out left to right.
barn.column1–2A container that lays its children out top to bottom.
barn.label1–2Text that cannot be edited.
barn.button1–2A push button.
barn.input1–2A single-line text field.
barn.text_area1–2A multi-line text editor with scrollbars.
barn.list1–2A list of selectable rows.
barn.checkbox1–2A checkbox.
barn.spacer1–2Empty space that takes a share of the layout.
barn.menu2A menu on the window's menu bar.
barn.item2–3An entry in a menu. Fires click.
barn.separator1A dividing line in a menu.
barn.on3Register a handler: "click", "change", "select", "toggle" or "close".
barn.text1The widget's current text.
barn.set_text2Replace the widget's text.
barn.items1A list's rows, as an array of strings.
barn.set_items2Replace a list's rows.
barn.selected1The selected row's index, or -1.
barn.select2Select a row by index.
barn.checked1Whether a checkbox is ticked.
barn.set_checked2Tick or untick a checkbox.
barn.enable2Enable or disable a widget.
barn.focus1Give a widget keyboard focus.
barn.title2Set a window's title.
barn.show1Put a window on screen.
barn.run0Run the event loop until every window has closed.
barn.close1Close a window.
barn.quit0Close every window, ending the event loop.
barn.alert2–3Show a message box.
barn.confirm2–3Ask a yes/no question. Returns true for yes.
barn.open_file0–2Ask for a file to open. Returns a path, or nil if cancelled.
barn.save_file0–2Ask where to save. Returns a path, or nil if cancelled.
barn.every2Call a function every n milliseconds. Returns a timer id.
barn.after2Call a function once, n milliseconds from now. Returns a timer id.
barn.cancel1Stop a timer, by the id every or after returned.
barn.clipboard0The clipboard's text, or nil.
barn.set_clipboard1Put text on the clipboard.

Missing something? The standard library is deliberately small: see ROADMAP.md for what is planned, and CONTRIBUTING.md for how to add it.