The Bach Programming Language

$ bach -q '"Hello world!" out'
Hello world!

Welcome to Bach, an experimental compositional programming language. Bach is a tool that enhances your command-line superpowers and helps you write concise, readable, and safe one-liners for text processing and other tasks. This book serves as an introduction and reference.

Introduction

In this introductory chapter, you can read about why I created Bach, and about its general design: Why Bach?

Alternatively, you can jump straight into trying Bach out with the sections on Installation and First Steps.

Why Bach?

Bach is a general-purpose programming language designed in particular for writing “one-liners” for text processing on the command line. It is designed to have the following properties:

  • Concise. One-liners are quick to type, there is not much boiler plate.
  • Readable. Bach programs consist mostly of English words. Bach makes minimal use of special characters. You can read a Bach program and get an idea of what it does even without being familiar with the language.
  • Flowing. Bach programs are evaluated from left to right, and can be read and understood thus.
  • Orthogonal. Bach’s language elements are designed so that there is one – and preferably only one – obvious way to do any given task. This makes life easier for both writers and readers of Bach programs. When in doubt, orthogonality trumps conciseness.

A Bach program is a series of functions. They are just written next to each other with spaces in between. Each function’s output is the next function’s input. In technical terms, a Bach program is a composition of its component functions. Schematically, this Bach program

f g h

corresponds to this expression in a traditional applicative programming language,

h(g(f))

and to this Unix pipeline:

f | g | h

In Bach, the concept of function composition is so central that there is no operator for it (like | in Unix shells or . in Haskell). It’s just what you get when you put two or more functions next to each other.

Installation

Unix-like systems

To install (or upgrade) Bach, install Go first. Then run:

go install github.com/texttheater/bach@latest

This will place the bach executable in $GOROOT/bin, thus in $HOME/go/bin by default. You may want to place it on your $PATH.

Windows

TBD

First Steps

The CLI

Call Bach and pass a Bach program to it as an argument on the command line. In our first example, our program consists of the string "Hello world!". Bach string literals use double quotes, so surround your program with single quotes.

$ bach '"Hello world!"'
"Hello world!"

Our program creates the string "Hello world!", and Bach shows this result to us, formatted as a string literal. If we want to print the message without the quotes, we can compose our pogram with the function out to print it out:

$ bach '"Hello world!" out'
Hello world!
"Hello world!"

out returns its input value unchanged, so we are still shown the string with the quotes at the end. To suppress this, we can call Bach with the -q flag:

$ bach -q '"Hello world!" out'
Hello world!

The REPL

Let us now use Bach in interactive mode by using its read-eval-print loop (REPL). To start it, we call Bach without an argument. Now we are shown the Bach prompt:

$ bach
bach>

Let us again create the string "Hello world!":

bach> "Hello world!"
"Hello world!"

Now let us compose this program with the function codePoints, which gives us the list of Unicode code points in the string:

bach> "Hello world!" codePoints
[72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33]

Let us add another function, len, to compute the length of the string (in terms of code points):

bach> "Hello world!" codePoints len
12

As a final example in this introduction, let us add 1 and 2:

bach> 1 +(2)
3

Bach does not have infix operators. + is just a function that takes an input value (1) and an argument (2). Arguments are given in parentheses. However, for the mathematical operators, you can leave the parentheses out. Note however, that you can't have a space between the + and the 2:

bach> 1 +2
3

To exit the REPL, press Ctrl+D.

Types

Bach has null, boolean, number, string, array, object, and union types. Additionally, there is the Void type (there are no values of this type) and the Any type (all values are of this type). If you are wondering what the output type of your program is, you can always compose it with the type function, and you will get a string representation of the output type.

The following table demonstrates this: in the Program column, there are a number of Bach programs, each consisting of some expression followed by the type function. The Type column indicates the output type of the whole program. Here, it’s always Str because that is the output type of type. Finally, the Value column contains the strings representing the types of the various expressions.

ProgramTypeValueError
null typeStr"Null"
false typeStr"Bool"
true typeStr"Bool"
42 typeStr"Num"
0.3 typeStr"Num"
"Hello world!" typeStr"Str"
[] typeStr"Arr<>"
{} typeStr"Obj<Void>"
for Any def f Num|Str as 0 ok f typeStr"Num|Str"
for Any def f Any as null ok f typeStr"Any"

Simple Types

The simple types in Bach are Null, Bool, Num, and Str. The following table shows some examples of programs that evaluate to a value of each type.

ProgramTypeValueError
nullNullnull
falseBoolfalse
trueBooltrue
42Num42
0.3Num0.3
"Hello world!"Str"Hello world!"

The Null type has a single value, null.

The are two Bool values: true and false.

Num values are IEEE754 double-precision floating-point numbers.

Str values are sequences of bytes.

Array Types

The type of an array is written as Arr<>. Between the angle brackets, the types of the array's elements are listed. If the last element type is followed by an ellipsis, this means that the length of the array is unknown and that there can be 0, 1, or more elements of this type here. Array functions such as each(...) usually return arrays with an unknown number of elements.

ProgramTypeValueError
[]Arr<>[]
[1]Arr<Num>[1]
[1, 2, 3]Arr<Num, Num, Num>[1, 2, 3]
[1, 2, 3] each(+1)Arr<Num...>[2, 3, 4]
[1, "a"]Arr<Num, Str>[1, "a"]
[[1, 2], ["a", "b"]]Arr<Arr<Num, Num>, Arr<Str, Str>>[[1, 2], ["a", "b"]]
[1;[]]Arr<Num>[1]
[1, 2;[3, 4]]Arr<Num, Num, Num, Num>[1, 2, 3, 4]
[3, 4] =rest [1, 2;rest]Arr<Num, Num, Num, Num>[1, 2, 3, 4]
[1, 2;[1, 2] each(+2)]Arr<Num, Num, Num...>[1, 2, 3, 4]
for Arr<Any...> def f Arr<Any...> as id ok [] fArr<Any...>[]

Object Types

An object is a unique mapping from strings (“properties”) to values. The most general object type is Obj<Any>. A more restrictive type can be specified for all values, e.g., Obj<Str>. If specific properties and their types are known, this can be part of the type too, e.g.: Obj<a: Num, b: Num, Str>. The type at the end then describes all other values.

ProgramTypeValueError
{}Obj<Void>{}
{a: 1}Obj<a: Num, Void>{a: 1}
{a: 1, b: "c"}Obj<a: Num, b: Str, Void>{a: 1, b: "c"}
for Any def f Obj<Num> as {a: 1, b: 2} ok fObj<Num>{a: 1, b: 2}
for Any def f Obj<Any> as {a: 1, b: "c"} ok fObj<Any>{a: 1, b: "c"}
for Any def f Obj<a: Num, b: Str, Any> as {a: 1, b: "c", d: false} ok fObj<a: Num, b: Str, Any>{a: 1, b: "c", d: false}

Union Types

A union type indicates that a value could be of any of two or more types.

ProgramTypeValueError
[1] +["a"]Arr<Num|Str...>[1, "a"]
[1] +["a"] get(0)Num|Str1

Expressions

In Bach, every expression denotes a function. For example:

  • 2 denotes a function that takes any input, ignores it, and returns the number 2.
  • join(",") denotes a function that takes a list of strings and concatenates them, using the comma as a separator.
  • +(2) denotes a function that takes a number as input, adds 2 to it, and returns the result.
  • +2 is the same, with syntactic sugar applied.
  • if %3 ==0 then "multiple of 3" else "not a multiple of 3" ok denotes a function that takes a number and returns different strings depending on whether the number is divisible by 3.
  • +2 *3 denotes a composition of two functions, which is, again, a function (one that takes a number, adds 2 to it, then multiplies the result by 3).

This chapter describes the different kinds of expressions in more detail.

Literal Expressions

Num Literals

Nonnegative real numbers can be written in the decimal system: as integers, with a decimal point, or in exponential notation.

ProgramTypeValueError
123Num123
1.23Num1.23
01.23Num1.23
.23Num0.23
1.Num1
1.23e2Num123
123E2Num12300
123E+2Num12300
1e-1Num0.1
.1e0Num0.1
0010e-2Num0.1
0e+5Num0

There are no literals for negative, infinity, or NaN values. But they can be created using the builtin -, inf, and nan funcers. For details, see Math Funcers.

ProgramTypeValueError
-1Num-1
-0010e-2Num-0.1
-0Num-0
infNuminf
-infNum-inf
nanNumnan

Str Literals

Strings are sequences of bytes. String literals are delimited by double quotes. Characters inside generally represent the byte sequence that is their UTF-8 encoding. For example:

  • a represents the byte sequence 61 (hexadecimal notation; UTF-8 encoding of Latin Small Letter A)
  • ~ represents the byte sequence 7E (UTF-8 encoding of Tilde)
  • abc represents the byte sequence 61 62 63
  • 日本語 represents the byte sequence E6 97 A5 E6 9C AC E8 AA 9E

There are, however, the following exceptions:

  • \a represents the byte sequence 07 (UTF-8 encoding of Bell character)
  • \b represents the byte sequence 08 (UTF-8 encoding of Backspace)
  • \f represents the byte sequence 0C (UTF-8 encoding of Form feed)
  • \n represents the byte sequence 0A (UTF-8 encoding of Line feed)
  • \r represents the byte sequence 0D (UTF-8 encoding of Carriage return)
  • \t represents the byte sequence 09 (UTF-8 encoding of Horizontal tab)
  • \v represents the byte sequence 09 (UTF-8 encoding of Vertical tab)
  • \\ represents the byte sequence 5C (UTF-8 encoding of Backslash)
  • \" represents the byte sequence 22 (UTF-8 encoding of Quotation mark)
  • \ followed by three octal digits in the range from 000 to 3ff (inclusive) represents the corresponding byte
  • \x followed by two hexadecimal digits represents the corresponding byte
  • \u followed by four hexadecimal digits represents the UTF-8 encoding of the corresponding code point, if defined
  • \U followed by eight hexadecimal digits represents the UTF-8 encoding of the corresponding code point, if defined
  • {{ represents the byte sequence 7B (UTF-8 encoding of Left curly bracket)
  • }} represents the byte sequence 7D (UTF-8 encoding of Right curly bracket)
  • {, followed by a Bach expression, followed by }, represents the UTF-8 encoding of what the expression evaluates to
  • Other uses of \, ", {, or } inside the delimiting quotes are invalid, as is the line feed character
ProgramTypeValueError
"a"Str"a"
"\a"Str"\a"
"\"\\a\""Str"\"\\a\""
"\141"Str"a"
"\x61"Str"a"
"\u65e5\u672c\u8a9e"Str"日本語"
"\U000065e5\U0000672c\U00008a9e"Str"日本語"
"{{}}"Str"{{}}"
"1 + 1 = {1 +1}"Str"1 + 1 = 2"
"{ {a: 1 +1} }"Str"{{a: 2}}"

Arr Literals

Array literals are delimited by square brackets. Inside, a comma-separated sequence of Bach expressions represents the elements. An expression representing an array can be appended as a suffix using a semicolon.

ProgramTypeValueError
[]Arr<>[]
[1]Arr<Num>[1]
[1, 2, 3]Arr<Num, Num, Num>[1, 2, 3]
[1, "a"]Arr<Num, Str>[1, "a"]
[[1, 2], ["a", "b"]]Arr<Arr<Num, Num>, Arr<Str, Str>>[[1, 2], ["a", "b"]]
[1 +1]Arr<Num>[2]
[1;[]]Arr<Num>[1]
[1, 2;[3, 4]]Arr<Num, Num, Num, Num>[1, 2, 3, 4]
[3, 4] =rest [1, 2;rest]Arr<Num, Num, Num, Num>[1, 2, 3, 4]
[1, 2;[1, 2] each(+2)]Arr<Num, Num, Num...>[1, 2, 3, 4]

Obj Literals

Obj literals are delimited by curly braces. Inside, each elements consists of a key, followed by a colon, followed by a value. Elements are separated by commas. The order of elements does not matter. Keys are always strings, but they can be written as identifiers or number literals; they are converted to strings automatically.

ProgramTypeValueError
{}Obj<Void>{}
{"a": 1}Obj<a: Num, Void>{a: 1}
{a: 1}Obj<a: Num, Void>{a: 1}
{1: "a"}Obj<1: Str, Void>{1: "a"}
{"1": "a"}Obj<1: Str, Void>{1: "a"}
{a: 1, b: "c"}Obj<a: Num, b: Str, Void>{a: 1, b: "c"}
{b: 1 +1}Obj<b: Num, Void>{b: 2}

Funcer Call Expressions

Every Bach expression denotes a function that maps the input to the output. Funcers are generalizations of functions: in addition to the input, they can have arguments on which their output depends. But there are also 0-argument funcers. A number of funcers are built-in to Bach (see Builtin Funcer Reference), and you can define your own (see Funcer Definition Expressions). Arguments go between parentheses. No space is allowed between the funcer name and the opening parenthesis. For example, len returns the length of an array, join joins a list of strings with a given glue string, and +(1) adds 1 to a number.

ProgramTypeValueError
[1, 2, 3] lenNum3
["a", "b", "c"] join("+")Str"a+b+c"
1 +(1)Num2

Syntactic Sugar

To make arithmetic expressions etc. less noisy, when calling the funcers +, -, *, /, %, <, >, ==, <=, >=, ** with one argument that is a single literal or funcer call, the parentheses can be omitted. Note that there are no operator precedence rules in Bach – evaluation is from left to right. To change precedence, put arguments in parentheses by not omitting the parentheses.

ProgramTypeValueError
1 +1Num2
2 +3 *5Num25
2 +(3 *5)Num17

With a single argument that is a string, regexp, array, or object literal, parentheses may also be omitted.

ProgramTypeValueError
["a", "b", "c"] join"+"Str"a+b+c"

Overloading

Funcers are selected according to the input type, the name, and the number of arguments. For example, there are two builtin 1-arg funcers named +: one for Num inputs (which expects the first argument to evaluate to a Num and returns the sum) and one for Str inputs (which expectes the first argument to evaluate to a Str and returns the concatenation).

ProgramTypeValueError
1 +2Num3
"a" +"b"Str"ab"
"a" +2Type error
Code: ArgHasWrongOutputType
Message: An argument has the wrong output type.
Want type: Str
Got type: Num
Arg #: 1

Partial Application

In most cases, funcers are defined so that their argument can be any type of expression as long as it has the right input and output type. But it is also possible for funcer parameters to require a partially applied funcer call with n remaining arguments to be filled in by the funcer. To call a funcer with m+n arguments to fill a parameter that requires n open arguments, pass only the first m arguments. As an example with m=0 and n=1, the builtin funcer sort takes a comparison funcer with an open argument as its sole argument. Here, we use the number comparison funcer >:

ProgramTypeValueError
[7, 3, 2, 5] sort(>)Arr<Num...>[7, 5, 3, 2]

Funcer Definition Expressions

To define a funcer, use a funcer definition expression. It has the form for I def N(P1, P2, ..., Pn) O as B ok, where I is the funcer’s input type, N is its name (must start with a lower-case letter), P1, P2, ..., Pn are n or more parameters (if n=0, leave out the parentheses), O is the funcer’s output type, and B is its body. When called, the funcer will evaluate like B, with parameters bound to the arguments passed at call time.

Here are some examples of defining and then calling funcers without parameters:

ProgramTypeValueError
for Num def plusOne Num as +1 ok 1 plusOneNum2
for Num def plusOne Num as +1 ok 1 plusOne plusOneNum3

Parameters

In addition to the input, funcers can take arguments, which are functions that can be called in the funcer body to use their outputs. Parameters specify what kind of arguments are expected. In the simplest case, a parameter is simply a name and a type. This means that inside the funcer body, the given function can be called with any input, by the given name, and will return a value of the given type.

ProgramTypeValueError
for Any def f(x Num) Num as x ok f(1)Num1
for Num def plus(b Num) Num as +b ok 1 plus(1)Num2
for Any def f(a Num, b Num) Arr<Num, Num> as [a, b] ok f(2, 3)Arr<Num, Num>[2, 3]

Parameters with Parameters

In more complex cases, parameters can restrict arguments to be partially applied funcer calls. In such cases, the syntax for a parameter is for I N(P1, P2, ..., Pn) O. This means that inside the funcer body, for inputs of type I, the given funcer will be available to call by the name N with arguments as specified by the parameters P1, P2, ..., Pn (as before, drop the parentheses if n=0) and will return a value of type O. Here, P1, P2, ..., Pn do not contain names.

ProgramTypeValueError
for Num def apply(for Num f Num) Num as f ok 1 apply(+1)Num2
for Num def apply(for Num f Num) Num as f ok 2 =n apply(+n)Num4
for Num def connectSelf(for Num f(for Any Num) Num) Num as =x f(x) ok 1 connectSelf(+)Num2
for Num def connectSelf(for Num f(for Any Num) Num) Num as =x f(x) ok 3 connectSelf(*)Num9
for Num def connectSelf(for Num f(Num) Num) Num as =x f(x) ok 1 connectSelf(+)Num2

Type Variables

Funcer definition expressions can use type variables. They are written between angle brackets and start with an upper-case letter. When applying a funcer to an input expression, type variables are bound from left to right.

ProgramTypeValueError
for <A> def apply(for <A> f <B>) <B> as f ok 1 apply(+1)Num2
for <A>|Null def myMust <A> as is Null then fatal else id ok ok 123 myMustNum123
for <A>|Null def myMust <A> as is Null then fatal else id ok ok "abc" myMustStr"abc"
for <A>|Null def myMust <A> as is Null then fatal else id ok ok null myMust<A>Value error
Code: UnexpectedValue
Message: Component got an unexpected input value.
Got value: null
for <A>|Null def myMust <A> as is <A> then id else fatal ok ok null myMustNullnull
for <A Obj<a: Num, Any>> def f <A> as id ok {a: 1} fObj<a: Num, Void>{a: 1}

Type Variables with Bounds

Type variables can be given upper bounds, they are then constrained to match subtypes of the given upper bound type.

ProgramTypeValueError
for Any def f(for Any g <A Arr<Any...>>) <A> as g ok f([1, "a"])Arr<Num, Str>[1, "a"]
for Any def f(for Any g <A Arr<Any...>>) <A> as g ok f("a")Type error
Code: ArgHasWrongOutputType
Message: An argument has the wrong output type.
Want type: <A Arr<Any...>>
Got type: Str
Arg #: 1

Overloading, Revisited

Funcers are looked up by input type, name, and number of parameters. So you can, for example, define two funcers with the same name but different input types, and use both:

ProgramTypeValueError
for Num def f Num as +2 ok for Str def f Str as +"2" okNullnull
for Num def f Num as +2 ok for Str def f Str as +"2" ok 2 fNum4
for Num def f Num as +2 ok for Str def f Str as +"2" ok "a" fStr"a2"

Funcers cannot be overloaded with respect to the parameters themselves. Thus, calling a funcer on the wrong input or with the wrong number of arguments results in a NoSuchFuncer error. Calling it with the wrong kinds of arguments, by contrast, leads to an ArgHasWrongOutputType error.

ProgramTypeValueError
for Num def f Num as *2 ok fType error
Code: NoSuchFuncer
Message: no such funcer
Input type: Null
Name: f
# params: 0
for <A Obj<a: Num>> def f <A> as id ok {} fType error
Code: NoSuchFuncer
Message: no such funcer
Input type: Obj<Void>
Name: f
# params: 0
for Num def f Num as *2 ok 2 f(2)Type error
Code: NoSuchFuncer
Message: no such funcer
Input type: Num
Name: f
# params: 1
for Str def f Obj<> as {} ok "abc" reFindAll(f)Type error
Code: ArgHasWrongOutputType
Message: An argument has the wrong output type.
Want type: <A Null|Obj<0: Str, start: Num, Any>>
Got type: Obj<Any>
Arg #: 1

Variable Capturing

Funcers have access to the variables defined before, but not after the definition.

ProgramTypeValueError
1 =a for Any def f Num as a ok fNum1
1 =a for Any def f Num as a ok 2 =a fNum1
1 =a for Any def f Num as 2 =a a ok fNum2

Recursion

TBD

Assignment Expressions

An assignment expressions consists of the character = immediately followed by a pattern. It binds the names in the pattern to the corresponding parts of its input value so you can reuse them later in the program. A pattern can be a name, an array literal where the elements are patterns, or an object literal where the values are patterns.

ProgramTypeValueError
1 +1 =a 3 *2 +aNum8
1 +1 ==2 =p 1 +1 ==1 =q p ==q notBooltrue
[1, 2, 3] =[a, b, c] aNum1
[1, 2, 3] =[a;r] rArr<Num, Num>[2, 3]
{a: 1, b: 2, c: 3} ={a: d, b: e, c: f} dNum1
{a: 1, b: 2, c: 3} ={a: d, b: e, c: f} eNum2
{a: 1, b: 2, c: 3} ={a: d, b: e, c: f} fNum3
for Num def cube Num as =n *n *n ok 3 cubeNum27

An “impossible match” error occurs if the pattern cannot match any values of the input type, e.g., if an array pattern has a different length from the input, or matching objects with array patterns, or vice versa, or if an object pattern contains keys that the input doesn’t.

ProgramTypeValueError
[1, 2, 3] =[a, b]Type error
Code: ImpossibleMatch
Message: Impossible match. The pattern will never match the input type.
{a: 1, b: 2, c: 3} =[a, b]Type error
Code: ImpossibleMatch
Message: Impossible match. The pattern will never match the input type.
{a: 1, b: 2, c: 3} ={g: h}Type error
Code: ImpossibleMatch
Message: Impossible match. The pattern will never match the input type.

A “nonexhaustive match” error occurs if the pattern can match some but not all values of the input type, e.g., if a variable-length array type is matched as fixed-length, or if an object type is matched against a key it might or might not contain.

ProgramTypeValueError
for Arr<Num...> def f Num as =[a, b] a okType error
Code: NonExhaustiveMatch
Message: Match is not exhaustive. Consider adding elis clauses and/or an else clause.
for Obj<a: Num, Num> def f Num as ={a: a, b: b} a +b okType error
Code: NonExhaustiveMatch
Message: Match is not exhaustive. Consider adding elis clauses and/or an else clause.
for Obj<a: Num, Num> def f Num as ={b: b} b okType error
Code: NonExhaustiveMatch
Message: Match is not exhaustive. Consider adding elis clauses and/or an else clause.

Conditional Expressions

Conditional expressions come in three flavors:

  • if A then B else C ok (checks a boolean condition A)
  • is A then B else C ok (matches the input against the pattern A)
  • is A with D then B else C ok (matches the input against the pattern A and checks the boolean condition D)

A pattern can be a name, a type optionally combined with a name, an array literal where the elements are patterns, or an object literal where the values are patterns.

To check for additional alternative conditions, add alternative clauses before the final else clause. Alternative clauses, too, come in three flavors. All can be freely combined:

  • elis A then B (checks a boolean condition A)
  • elis A then B (matches the input against the pattern A)
  • elis A with D then B (matches the input against the pattern A and checks the boolean condition D)

Names bound by a pattern can be used inside the following then clause.

ProgramTypeValueError
if true then 2 else 3 okNum2
for Num def heart Bool as if <3 then true else false ok ok 2 heartBooltrue
for Num def heart Bool as if <3 then true else false ok ok 4 heartBoolfalse
for Num def expand Num as if <0 then -1 elif >0 then +1 else 0 ok ok 0 -1 expandNum-2
for Num def expand Num as if <0 then -1 elif >0 then +1 else 0 ok ok 1 expandNum2
for Num def expand Num as if <0 then -1 elif >0 then +1 else 0 ok ok 0 expandNum0

Predicate Expressions

In Bach, a predicate is a function that for a given input I returns either {yes: I} or {no: I}. This is often useful, e.g., for checking the members of an array for some condition. Thus, several builtin array funcers accept them as arguments.

Bach provides a special syntax for making such conditions easy to write. A predicate expression is like a conditional expression, except it consists only of the first part, that is, the if ... clause, or the is ... clause, or the is ... with ... clause. The then {yes: id} else {no: id} part is filled in automatically.

ProgramTypeValueError
is NullType error
Code: UnreachableElseClause
Message: The else clause is unreachable because the match is already exhaustive.
2 is Num with >3Obj<yes: Num>|Obj<no: Num>{no: 2}
4 is Num with >3Obj<yes: Num>|Obj<no: Num>{yes: 4}
2 if >3Obj<yes: Num>|Obj<no: Num>{no: 2}
4 if >3Obj<yes: Num>|Obj<no: Num>{yes: 4}
for Any def f Num|Str as 2 ok f is Num _Obj<yes: Num>|Obj<no: Str>{yes: 2}
[1, 2, 3] each(if ==1 then "a" elif ==2 then "b" else "c" ok)Arr<Str...>["a", "b", "c"]
[1, 2, 3] each(if ==1 then "a" elif ==2 then "b" else "c")Syntax error
Code: Syntax
Message: syntax error

Getter Expressions

A getter expressions consists of the @ character followed by an object property name or an array index. It retrieves the value of the property or the element at the index for an input object or array. The input type must guarantee the existence of the property/index, otherwise a type error is raised. If the input type cannot guarantee the existence of the property/index, use the get funcer for objects or for arrays.

ProgramTypeValueError
{a: 1, b: 2} @aNum1
{a: 1, b: 2} @bNum2
{a: 1, b: 2} @cType error
Code: NoSuchProperty
Message: The object does not have this property.
Want type: Obj<c: Any, Any>
Got type: Obj<a: Num, b: Num, Void>
{0: "a"} @0Str"a"
["a", "b", "c"] @0Str"a"
["a", "b", "c"] @1Str"b"
["a", "b", "c"] @2Str"c"
["a", "b", "c"] @3Type error
Code: NoSuchIndex
Message: Array is not long enough.
["a", "b", "c"] @-1Type error
Code: BadIndex
Message: Index must be a nonnegative integer.
["a", "b", "c"] @1.5Type error
Code: BadIndex
Message: Index must be a nonnegative integer.
"abc" @1Type error
Code: NoGetterAllowed
Message: A getter expression cannot be applied to this type.
24 @1Type error
Code: NoGetterAllowed
Message: A getter expression cannot be applied to this type.
for Any def f Arr<Any...> as [] ok f @1Type error
Code: NoGetterAllowed
Message: A getter expression cannot be applied to this type.

Regexp Expressions

In Bach, a regexp is a function that takes a Str and returns either null or an object with at least a property start with type Num, and 0 with type Str.

Regexp expressions denote such functions. They have the syntax of re2 regular expressions, except for \C, delimited by ~. They search the input string for a substring that matches the regular expression. If none can be found, null is returned. Otherwise, an object is returned with start indicating the offset (in codepoints) of the first occurrence, and 0 containing the matched substring. If the regexp contains capturing groups, the substrings matched by the groups are included as additional properties – by group number and, in the case of named groups, additionally by name.

ProgramTypeValueError
"abccd" ~b(?P<cs>c*)d~Null|Obj<start: Num, 0: Str, 1: Null|Str, cs: Null|Str, Void>{start: 1, 0: "bccd", 1: "cc", cs: "cc"}
"def" ~^b(?P<cs>c*)d~Null|Obj<start: Num, 0: Str, 1: Null|Str, cs: Null|Str, Void>null
"abccd" ~^b(?P<cs>*)d~Syntax error
Code: BadRegexp
Message: error parsing regexp

Regexp expressions can be used with regexp funcers for greater effect.

Composition Expressions

A composition expression consists of two other expressions, separated by whitespace. The output of the first expression is then used as the input to the other. By adding another expression at the end, you again create a larger composition expression, and so on.

ProgramTypeValueError
"abc"Str"abc"
"abc" codePointsArr<Num...>[97, 98, 99]
"abc" codePoints lenNum3
"abc" codePoints len *3Num9

Note that when you compose with expressions that ignore their input, such as literals, only the last one has any effect on the output.

ProgramTypeValueError
1Num1
1 2Num2
1 2 3.5Num3.5

Builtin Funcer Reference

Null Funcers

null

Returns the null value.

TypeValue
InputAnyany value (is ignored)
OutputNullthe null value (the only value of this type)

Examples

ProgramTypeValueError
nullNullnull
1 nullNullnull

I/O Funcers

blocks

Groups lines into blocks separated by empty lines.

TypeValue
InputArr<Str...>an array of consecutive lines
OutputArr<Arr<Str...>...>an array of arrays of lines, each representing a block

Each empty line in the input marks the end of a block. Blocks can be empty. The empty lines themselves are not included.

Examples

ProgramTypeValueError
["a", "b", "", "c", "d", "e", "f", ""] blocksArr<Arr<Str...>...>[["a", "b"], ["c", "d", "e", "f"]]
["a", ""] blocksArr<Arr<Str...>...>[["a"]]
["a"] blocksArr<Arr<Str...>...>[["a"]]
["", "a"] blocksArr<Arr<Str...>...>[[], ["a"]]
["a", "", "", "", "b"] blocksArr<Arr<Str...>...>[["a"], [], [], ["b"]]

err

Writes to STDERR.

TypeValue
Input<A Any>any value
Output<A Any>the same value

Identity function with the side effect of writing a string representation of the value to STDERR, followed by a line break.

Examples

ProgramTypeValueError

err

Writes to STDERR with a custom line end.

TypeValue
Input<A Any>any value
end (param #1)Strthe line end to use
Output<A Any>the same value

Identity function with the side effect of writing a string representation of the value to STDERR, followed by a the specified line end.

Examples

ProgramTypeValueError

in

Reads from STDIN.

TypeValue
InputAnyany value (is ignored)
OutputReadera Reader representing STDIN

Examples

ProgramTypeValueError

json

Reads JSON values from a stream

TypeValue
InputReadera Reader
OutputArr<Any...>array of data structures as they appear in the stream

Examples

ProgramTypeValueError

lines

Reads a stream line-by-line

TypeValue
InputReadera Reader
OutputArr<Str...>an array of lines, without the line-break character

Examples

ProgramTypeValueError
"abc\nde\n\nf" reader linesArr<Str...>["abc", "de", "", "f"]

out

Writes to STDOUT.

TypeValue
Input<A Any>any value
Output<A Any>the same value

Identity function with the side effect of writing a string representation of the value to STDERR, followed by a line break.

Examples

ProgramTypeValueError

out

Writes to STDOUT with a custom line end.

TypeValue
Input<A Any>any value
end (param #1)Str
Output<A Any>the same value

Identity function with the side effect of writing a string representation of the value to STDOUT, followed by a line break.

Examples

ProgramTypeValueError

reader

Creates a Reader from a Str.

TypeValue
InputStra string
OutputReadera Reader from which the input can be read

Examples

ProgramTypeValueError

Logic Funcers

true

Returns the value representing logical truth.

TypeValue
InputAnyany value (is ignored)
OutputBoolthe unique value representing logical truth

Examples

ProgramTypeValueError
trueBooltrue

false

Returns the value representing logical falsehood.

TypeValue
InputAnyany value (is ignored)
OutputBoolthe unique value representing logical falsehood

Examples

ProgramTypeValueError
falseBoolfalse

and

Computes logical conjunction.

TypeValue
InputBoola boolean value
q (param #1)Boolanother boolean value
OutputBooltrue if both the input and q are true, false otherwise

Examples

ProgramTypeValueError
false and(false)Boolfalse
false and(true)Boolfalse
true and(false)Boolfalse
true and(true)Booltrue

or

Computes logical disjunction.

TypeValue
InputBoola boolean value
q (param #1)Boolanother boolean value
OutputBooltrue if at least one of the input and q is true, false otherwise

Examples

ProgramTypeValueError
false or(false)Boolfalse
false or(true)Booltrue
true or(false)Booltrue
true or(true)Booltrue

not

Computes logical negation.

TypeValue
InputBoola boolean value
OutputBooltrue if the input is false, and false if the input is true

Examples

ProgramTypeValueError
false notBooltrue
true notBoolfalse
1 +1 ==2 and(2 +2 ==5 not)Booltrue

==

Checks equality of boolean values.

TypeValue
InputBoola boolean value
q (param #1)Boolanother boolean value
OutputBooltrue if the input and q are identical, false otherwise

Examples

ProgramTypeValueError
false ==falseBooltrue
false ==trueBoolfalse
true ==falseBoolfalse
true ==trueBooltrue

Math Funcers

+

Adds two numbers.

TypeValue
InputNumthe first summand
b (param #1)Numthe second summand
OutputNumthe sum

Examples

ProgramTypeValueError
1 +1Num2
1 +2 *3Num9
1 +(2 *3)Num7

-

Subtracts a number from another.

TypeValue
InputNumthe minuend
b (param #1)Numthe subtrahend
OutputNumthe difference

Examples

ProgramTypeValueError
5 -3Num2

-

Returns the additive inverse of a number.

TypeValue
InputAnyany value (is ignored)
n (param #1)Numa number
OutputNumthe additive inverse (opposite number) of n

Examples

ProgramTypeValueError
-1Num-1
-(-2.0)Num2
-infNum-inf
-nanNumnan

*

Multiplies two numbers.

TypeValue
InputNumthe first factor
b (param #1)Numthe second factor
OutputNumthe product

Examples

ProgramTypeValueError
2 *3Num6

/

Divides a number by another.

TypeValue
InputNumthe dividend
b (param #1)Numthe divisor
OutputNumthe quotient

Examples

ProgramTypeValueError
3 /2Num1.5
1 /0Numinf

%

Remainder

TypeValue
InputNumthe dividend
b (param #1)Numthe divisor
OutputNumthe remainder of integer division (rounded towards zero)

Examples

ProgramTypeValueError
3 %2Num1
-8.5 %3Num-2.5

<

Less than

TypeValue
InputNuma number
b (param #1)Numanother number
OutputBooltrue iff the input is smaller than b

Examples

ProgramTypeValueError
2 <1Boolfalse
-inf <infBooltrue
0 <0Boolfalse

>

Greater than

TypeValue
InputNuma number
b (param #1)Numanother number
OutputBooltrue iff the input is greater than b

Examples

ProgramTypeValueError
2 >1Booltrue
-inf >infBoolfalse
0 >0Boolfalse

<=

Less than or equal to

TypeValue
InputNuma number
b (param #1)Numanother number
OutputBooltrue iff the input is less than or equal to b

Examples

ProgramTypeValueError
2 <=1Boolfalse
-inf <=infBooltrue
0 <=0Booltrue

>=

Greater than or equal to

TypeValue
InputNuma number
b (param #1)Numanother number
OutputBooltrue iff the input is greater than or equal to b

Examples

ProgramTypeValueError
2 >=1Booltrue
-inf >=infBoolfalse
0 >=0Booltrue

sum

Computes the sum of several numbers.

TypeValue
InputArr<Num...>an array of numbers
OutputNumtheir sum

Examples

ProgramTypeValueError
[1, 2, 3, 4] sumNum10
[] sumNum0

median

Computes the median of several numbers.

TypeValue
InputArr<Num...>an array of numbers
OutputNumtheir median

Examples

ProgramTypeValueError
[2, 3, 7] medianNum3
[2, 3, 5, 7] medianNum4
[1.25] medianNum1.25
[] medianNumnan

mean

Computes the arithmetic mean (average) of several numbers.

TypeValue
InputArr<Num...>an array of numbers
OutputNumtheir mean

Examples

ProgramTypeValueError
[2, 3, 5, 7] meanNum4.25
[1.25] meanNum1.25
[] meanNumnan

inf

Returns infinity.

TypeValue
InputAnyany value (is ignored)
OutputNumthe special number value representing positive infinity

Examples

ProgramTypeValueError
infNuminf
-infNum-inf
inf +infNuminf
inf -infNumnan

nan

Returns NaN.

TypeValue
InputAnyany value (is ignored)
OutputNumthe special number value representing “not a number”

Examples

ProgramTypeValueError
nanNumnan
nan ==2Boolfalse
nan ==nanBoolfalse
-nanNumnan

isFinite

Checks whether a number is finite.

TypeValue
InputNuma number
OutputBooltrue unless the input is positive or negative infinity

Examples

ProgramTypeValueError
1024 isFiniteBooltrue
-1024 isFiniteBooltrue
inf isFiniteBoolfalse
-inf isFiniteBoolfalse
nan isFiniteBooltrue

isNaN

Checks whether a number is NaN.

TypeValue
InputNuma number
OutputBooltrue iff the input is NaN

Examples

ProgramTypeValueError
1024 isNaNBoolfalse
nan isNaNBooltrue

epsilon

Returns the floating point epsilon.

TypeValue
InputAnyany value (is ignored)
OutputNumthe difference between 1 and the smallest floating point number greater than 1

Examples

ProgramTypeValueError
epsilonNum2.220446049250313e-16

largestSafeInteger

Returns the largest safe integer.

TypeValue
InputAnyany value (is ignored)
OutputNumthe largest integer that can be represented as an IEEE-754 double precision number and cannot be the result of rounding another number to fit IEEE-754

Examples

ProgramTypeValueError
largestSafeInteger +0Num9007199254740991
largestSafeInteger +1Num9007199254740992
largestSafeInteger +2Num9007199254740992

largestNum

Returns the largest representable number.

TypeValue
InputAnyany value (is ignored)
OutputNumthe largest number representable as an IEEE-754 double precision number

Examples

ProgramTypeValueError
largestNumNum1.7976931348623157e+308
largestNum +largestNumNuminf

smallestSafeInteger

Returns the smallest safe integer.

TypeValue
InputAnyany value (is ignored)
OutputNumthe smallest integer that can be represented as an IEEE-754 double precision number and cannot be the result of rounding another integer to fit the IEEE-754 double precision representation

Examples

ProgramTypeValueError
smallestSafeInteger -0Num-9007199254740991
smallestSafeInteger -1Num-9007199254740992
smallestSafeInteger -2Num-9007199254740992

smallestPositiveNum

Returns the smallest representable positive number.

TypeValue
InputAnyany value (is ignored)
OutputNumthe smallest representable positive number

Examples

ProgramTypeValueError
smallestPositiveNumNum5e-324

isInteger

Checks whether a number is integer.

TypeValue
InputNuma number
OutputBooltrue iff the input represents a whole number

Examples

ProgramTypeValueError
1.0 isIntegerBooltrue
1.1 isIntegerBoolfalse

isSafeInteger

Checks whether a number is a safe integer.

TypeValue
InputNuma number
OutputBooltrue iff the input is an integer and cannot be the result of rounding another integer to fit the IEEE-754 double precision representation

Examples

ProgramTypeValueError
-9007199254740992 isSafeIntegerBoolfalse
-9007199254740991 isSafeIntegerBooltrue
0 isSafeIntegerBooltrue
0.1 isSafeIntegerBoolfalse
9007199254740991 isSafeIntegerBooltrue
9007199254740992 isSafeIntegerBoolfalse

toBase

Converts an integer to a specified base.

TypeValue
InputNuman integer
base (param #1)Numan integer between 2 and 36 (inclusive)
OutputStra string representation of the input in the specified base

Examples

ProgramTypeValueError
233 toBase(16)Str"e9"
11 toBase(16)Str"b"

toExponential

Converts a number to exponential notation.

TypeValue
InputNuma number
OutputStra string representation of the input in exponential notation with 6 digits after the decimal point

Examples

ProgramTypeValueError
77.1234 toExponentialStr"7.712340e+01"
77 toExponentialStr"7.700000e+01"

toExponential

Converts a number to exponential notation.

TypeValue
InputNuma number
precision (param #1)Numthe number of digits after the decimal point
OutputStra string representation of the input in exponential notation with the specified number of digits after the decimal point

Examples

ProgramTypeValueError
77.1234 toExponential(4)Str"7.7123e+01"
77.1234 toExponential(2)Str"7.71e+01"

toFixed

Converts a number to fixed-point notation.

TypeValue
InputNuma number
precision (param #1)Numthe number of digits after the decimal point
OutputStra rounded string representation of the input with the specified number of digits after the decimal point

Examples

ProgramTypeValueError
123.456 toFixed(2)Str"123.46"
0.004 toFixed(2)Str"0.00"
1.23e+5 toFixed(2)Str"123000.00"

e

Returns Euler's number.

TypeValue
InputAnyany value (is ignored)
OutputNuman approximation of Euler's number

Examples

ProgramTypeValueError
eNum2.718281828459045

ln2

Returns the natural logarithm of 2.

TypeValue
InputAnyany value (is ignored)
OutputNumthe approximate natural logarithm of 2

Examples

ProgramTypeValueError
ln2Num0.6931471805599453

ln10

Returns the natural logarithm of 10.

TypeValue
InputAnyany value (is ignored)
OutputNumthe approximate natural logarithm of 10

Examples

ProgramTypeValueError
ln10Num2.302585092994046

log2e

Returns the base-2 logarithm of e

TypeValue
InputAnyany value (is ignored)
OutputNumthe approximate base-2 logarithm of Euler's number

Examples

ProgramTypeValueError
log2eNum1.4426950408889634

log10e

Returns the base-10 logarithm of e

TypeValue
InputAnyany value (is ignored)
OutputNumthe approximate base-10 logarithm of Euler's number

Examples

ProgramTypeValueError
log10eNum0.4342944819032518

pi

Returns pi.

TypeValue
InputAnyany value (is ignored)
OutputNuman approximation of pi

Examples

ProgramTypeValueError
piNum3.141592653589793
for Num def radiusToCircumference Num as *2 *pi ok 10 radiusToCircumferenceNum62.83185307179586

sqrt1_2

Returns the square root of 1/2.

TypeValue
InputAnyany value (is ignored)
OutputNumthe approximate square root of 1/2

Examples

ProgramTypeValueError
sqrt1_2Num0.7071067811865476

sqrt2

Returns the square root of 2.

TypeValue
InputAnyany value (is ignored)
OutputNumthe approximate square root of 2

Examples

ProgramTypeValueError
sqrt2Num1.4142135623730951

abs

Computes the absolute value.

TypeValue
InputNuma number
OutputNumthe absolute value of the input

Examples

ProgramTypeValueError
3 -5 absNum2
5 -3 absNum2
1.23456 -7.89012 absNum6.6555599999999995

acos

Computes the inverse cosine.

TypeValue
InputNuma number in the interval [-1, 1]
OutputNumthe inverse cosine (in radians) of the input, or nan if the input is invalid

Examples

ProgramTypeValueError
-2 acosNumnan
-1 acosNum3.141592653589793
0 acosNum1.5707963267948966
1 acosNum0
1.1 acosNumnan

acosh

Computes the inverse hyperbolic cosine.

TypeValue
InputNuma number greater than or equal to 1
OutputNumthe inverse hyperoblic cosine of the input, or nan if the input is invalid

Examples

ProgramTypeValueError
0.9 acoshNumnan
1 acoshNum0
10 acoshNum2.993222846126381

asin

Computes the inverse sine.

TypeValue
InputNuma number in the interval [-1, 1]
OutputNumthe inverse sine (in radians) of the input, of nan if the input is invalid

Examples

ProgramTypeValueError
-2 asinNumnan
-1 asinNum-1.5707963267948966
0 asinNum0
1 asinNum1.5707963267948966
1.1 asinNumnan

asinh

Computes the inverse hyperbolic sine.

TypeValue
InputNuma number
OutputNumthe inverse hyperbolic sine of the input

Examples

ProgramTypeValueError
-1 asinhNum-0.881373587019543
0 asinhNum0
1 asinhNum0.881373587019543
2 asinhNum1.4436354751788103

atan

Computes the inverse tangent.

TypeValue
InputNuma number
OutputNumthe inverse tangent (in radians) of the input

Examples

ProgramTypeValueError
-10 atanNum-1.4711276743037345
-1 atanNum-0.7853981633974483
0 atanNum0
1 atanNum0.7853981633974483

atan2

Computes the angle in the plane.

TypeValue
InputNuma number y (y-coordinate)
x (param #1)Numa number (x-coordinate)
OutputNumthe angle in the plane (in radians) between the positive x-axis and the ray from (0, 0) to (x, y)

Examples

ProgramTypeValueError
5 atan2(5)Num0.7853981633974483
10 atan2(10)Num0.7853981633974483
10 atan2(0)Num1.5707963267948966

atanh

Computes the inverse hyperbolic tangent.

TypeValue
InputNuma number in the interval [-1, 1]
OutputNumthe inverse hyperbolic tangent of the input, or nan if the input is invalid

Examples

ProgramTypeValueError
-2 atanhNumnan
-1 atanhNum-inf
0 atanhNum0
0.5 atanhNum0.5493061443340548
1 atanhNuminf

cbrt

Computes the cube root.

TypeValue
InputNuma number
OutputNumthe cube root of the input

Examples

ProgramTypeValueError
-1 cbrtNum-1
1 cbrtNum1
inf cbrtNuminf
64 cbrtNum4

ceil

Rounds a number up.

TypeValue
InputNuma number
OutputNumthe smallest integer greater than or equal to the input

Examples

ProgramTypeValueError
.95 ceilNum1
4 ceilNum4
7.004 ceilNum8
-7.004 ceilNum-7

clz32

Count leading zeros.

TypeValue
InputNuma number (is truncated to integer)
OutputNumthe number of leading zero bits in the 32-bit binary representation of the input

Examples

ProgramTypeValueError
-inf clz32Num32
-4 clz32Num0
-1 clz32Num0
0 clz32Num32
0.5 clz32Num32
1 clz32Num31
1.1 clz32Num31
4 clz32Num29
4.7 clz32Num29
1000 clz32Num22
inf clz32Num32

cos

Computes the cosine.

TypeValue
InputNuman angle in radians
OutputNumthe cosine of the input

Examples

ProgramTypeValueError
-inf cosNumnan
-0 cosNum1
0 cosNum1
1 cosNum0.5403023058681398
pi cosNum-1
pi *2 cosNum1
inf cosNumnan

cosh

Computes the hyperbolic cosine.

TypeValue
InputNuma number
OutputNumthe hyperbolic cosine of the input

Examples

ProgramTypeValueError
0 coshNum1
1 coshNum1.5430806348152437
-1 coshNum1.5430806348152437
2 coshNum3.7621956910836314

exp

Computes the exponential function.

TypeValue
InputNumthe exponent
OutputNume (Euler's number) raised to the exponent

Examples

ProgramTypeValueError
-inf expNum0
-1 expNum0.36787944117144233
0 expNum1
1 expNum2.718281828459045
inf expNuminf

expm1

Computes the exponential function, subtracted by one.

TypeValue
InputNumthe exponent
OutputNum

e (Euler's number) raised to the exponent, minus 1

Examples

ProgramTypeValueError
-inf expm1Num-1
-1 expm1Num-0.6321205588285577
-0 expm1Num-0
0 expm1Num0
1 expm1Num1.718281828459045
inf expm1Numinf

floor

Rounds down.

TypeValue
InputNuma number
OutputNumthe largest integer less than or equal to the input

Examples

ProgramTypeValueError
5.95 floorNum5
5.05 floorNum5
5 floorNum5
-5.05 floorNum-6

fround

Rounds to 32-bit precision.

TypeValue
InputNuma number
OutputNumthe nearest 32-bit single precision float representation

Examples

ProgramTypeValueError
5.5 froundNum5.5
5.05 froundNum5.050000190734863
5 froundNum5
-5.05 froundNum-5.050000190734863

hypot

Computes the square root of the sum of squares

TypeValue
InputArr<Num...>an array of numbers
OutputNumthe square root of the sum of the squares of the input numbers

Examples

ProgramTypeValueError
[3, 4] hypotNum5
[5, 12] hypotNum13
[3, 4, 5] hypotNum7.0710678118654755
[-5] hypotNum5

imul

32-bit multiplication

TypeValue
InputNumthe first factor
y (param #1)Numthe second factor
OutputNumthe product of the 32-bit versions (cf. fround) of the factors

Examples

ProgramTypeValueError
3 imul(4)Num12
-5 imul(12)Num-60
"ffffffff" parseInt(16) imul(5)Num-5
"fffffffe" parseInt(16) imul(5)Num-10

log

Computes the natural logarithm.

TypeValue
InputNuma number
OutputNumthe natural (base e) logarithm of the input

Examples

ProgramTypeValueError
-1 logNumnan
-0 logNum-inf
0 logNum-inf
1 logNum0
10 logNum2.302585092994046
inf logNuminf
8 log /(2 log)Num3
625 log /(5 log)Num4

log10

Computes the base 10 logarithm.

TypeValue
InputNuma number
OutputNumthe base 10 logarithm of the input

Examples

ProgramTypeValueError
-2 log10Numnan
-0 log10Num-inf
0 log10Num-inf
1 log10Num0
2 log10Num0.3010299956639812
100000 log10Num5
inf log10Numinf

log1p

Computes the natural logarithm of x + 1.

TypeValue
InputNuma number (x)
OutputNum

the natural (base e) logarithm of (x + 1)

Examples

ProgramTypeValueError
1 log1pNum0.6931471805599453
0 log1pNum0
-1 log1pNum-inf
-2 log1pNumnan

log2

Computes the base 2 logarithm.

TypeValue
InputNuma number
OutputNumthe base 2 logarithm of the input

Examples

ProgramTypeValueError
3 log2Num1.5849625007211563
2 log2Num1
1 log2Num0
0 log2Num-inf

max

Finds the largest number

TypeValue
InputArr<Num...>an array of numbers
OutputNumthe largest number in the input, or -inf if the input is empty

Examples

ProgramTypeValueError
[1, 3, 2] maxNum3
[-1, -3, -2] maxNum-1
[] maxNum-inf

min

Finds the smallest number

TypeValue
InputArr<Num...>an array of numbers
OutputNumthe smallest number in the input, or inf if the input is empty

Examples

ProgramTypeValueError
[1, 3, 2] minNum1
[-1, -3, -2] minNum-3
[] minNuminf

**

Computes powers (exponentiation).

TypeValue
InputNumthe base
y (param #1)Numthe exponent
OutputNumthe base taken to the y-th power

Examples

ProgramTypeValueError
7 **3Num343
4 **.5Num2
7 **(-2)Num0.02040816326530612
-7 **0.5Numnan

random

Returns a random number between 0 and 1.

TypeValue
InputAnyany value (is ignored)
OutputNuma floating-point, pseudo-random number n with 0 <= n < 1 and approximately uniform distribution over that range

Examples

ProgramTypeValueError
[null] repeat(1000) each(random) each(>=0) allBooltrue
[null] repeat(1000) each(random) each(<1) allBooltrue

random

Returns a random integer number in a specified interval.

TypeValue
InputAnyany value (is ignored)
from (param #1)Numlower bound (inclusive); rounded towards 0 if not integer
to (param #2)Numupper bound (exclusive); rounded towards 0 if not integer
OutputNuma integer, pseudorandom number n with from <= n < to and approximately uniform distribution over that range

Examples

ProgramTypeValueError
[null] repeat(1000) each(random(2, 7)) each(>=2) allBooltrue
[null] repeat(1000) each(random(2, 7)) each(<7) allBooltrue
[null] repeat(1000) each(random(2, 7)) each(=n floor ==n) allBooltrue
[null] repeat(1000) each(random(2.4, 7.6)) each(>=2) allBooltrue
[null] repeat(1000) each(random(2.4, 7.6)) each(<7) allBooltrue
[null] repeat(1000) each(random(2.4, 7.6)) each(=n floor ==n) allBooltrue
[null] repeat(1000) each(random(-7, -2)) each(>=(-7)) allBooltrue
[null] repeat(1000) each(random(-7, -2)) each(<(-2)) allBooltrue
[null] repeat(1000) each(random(-7, -2)) each(=n floor ==n) allBooltrue
[null] repeat(1000) each(random(-7.6, -2.4)) each(>=(-7)) allBooltrue
[null] repeat(1000) each(random(-7.6, -2.4)) each(<(-2)) allBooltrue
[null] repeat(1000) each(random(-7.6, -2.4)) each(=n floor ==n) allBooltrue
random(7, 2)BoolValue error
Code: UnexpectedValue
Message: Component got an unexpected input value.
random(2, 2)BoolValue error
Code: UnexpectedValue
Message: Component got an unexpected input value.

round

Rounds a number to the nearest integer.

TypeValue
InputNuma number
OutputNumthe nearest integer, or away from zero if there's two nearest integers

Examples

ProgramTypeValueError
0.9 roundNum1
5.95 roundNum6
5.5 roundNum6
5.05 roundNum5
-5.05 roundNum-5
-5.5 roundNum-6
-5.95 roundNum-6

sign

Determines the sign of a number.

TypeValue
InputNuma number
OutputNum1 if the input is positive, -1 if negative, 0 if it's 0, and -0 if it's -0

Examples

ProgramTypeValueError
3 signNum1
0 signNum0
-0 signNum-0
-3Num-3

sin

Computes the sine.

TypeValue
InputNuman angle in radians
OutputNumthe sine of the input

Examples

ProgramTypeValueError
-inf sinNumnan
-0 sinNum-0
0 sinNum0
1 sinNum0.8414709848078965
pi /2 sinNum1
inf sinNumnan

sinh

Computes the hyperbolic sine.

TypeValue
InputNuma number
OutputNumthe hyperbolic sine of the input

Examples

ProgramTypeValueError
0 sinhNum0
1 sinhNum1.1752011936438014
-1 sinhNum-1.1752011936438014
2 sinhNum3.626860407847019

sqrt

Computes square roots.

TypeValue
InputNuma number
OutputNumthe square root of the input, or nan if it's negative

Examples

ProgramTypeValueError
-1 sqrtNumnan
-0 sqrtNum-0
0 sqrtNum0
1 sqrtNum1
2 sqrtNum1.4142135623730951
9 sqrtNum3
inf sqrtNuminf

tan

Computes the tangent.

TypeValue
InputNuman angle in radians
OutputNumthe tangent of the input

Examples

ProgramTypeValueError
0 *pi /180 tanNum0
45 *pi /180 tanNum1
90 *pi /180 tanNum16331239353195392

tanh

Computes the hyperbolic tangent.

TypeValue
InputNuma number
OutputNumthe hyperbolic tangent of the input

Examples

ProgramTypeValueError
-1 tanhNum-0.7615941559557649
0 tanhNum0
inf tanhNum1
1 tanhNum0.7615941559557649

trunc

Rounds towards zero.

TypeValue
InputNuma number
OutputNumthe input without fractional digits

Examples

ProgramTypeValueError
13.37 truncNum13
42.84 truncNum42
0.123 truncNum0
-0.123 truncNum-0

Text Funcers

<

Compares strings lexicographically.

TypeValue
InputStra string
other (param #1)Stranother string
OutputBooltrue if the input appears before other in lexicographical order, false otherwise

Examples

ProgramTypeValueError
"a" <"b"Booltrue
"Ab" <"A"Boolfalse
"cd" <"cd"Boolfalse

>

Compares strings lexicographically.

TypeValue
InputStra string
other (param #1)Stranother string
OutputBooltrue if the input appears after other in lexicographical order, false otherwise

Examples

ProgramTypeValueError
"a" >"b"Boolfalse
"Ab" >"A"Booltrue
"cd" >"cd"Boolfalse

<=

Compares strings lexicographically.

TypeValue
InputStra string
other (param #1)Stranother string
OutputBooltrue if the input appears before other in lexicographical order or is equal to it, false otherwise

Examples

ProgramTypeValueError
"a" <="b"Booltrue
"Ab" <="A"Boolfalse
"cd" <="cd"Booltrue

>=

Compares strings lexicographically.

TypeValue
InputStra string
other (param #1)Stranother string
OutputBooltrue if the input appears after other in lexicographical order or is equal to it, false otherwise

Examples

ProgramTypeValueError
"a" >="b"Boolfalse
"Ab" >="A"Booltrue
"cd" >="cd"Booltrue

+

Concatenates two strings.

TypeValue
InputStra string
b (param #1)Stranother string
OutputStrThe input and b, concatenated.

Examples

ProgramTypeValueError
"ab" +"cd"Str"abcd"
"ab" +""Str"ab"
"" +"cd"Str"cd"

bytes

Converts a string to bytes.

TypeValue
InputStra string
OutputArr<Num...>The UTF-8 bytes representing the string.

Examples

ProgramTypeValueError
"abc" bytesArr<Num...>[97, 98, 99]
"Köln" bytesArr<Num...>[75, 195, 182, 108, 110]
"日本語" bytesArr<Num...>[230, 151, 165, 230, 156, 172, 232, 170, 158]
"\x00" bytesArr<Num...>[0]

bytesToStr

Converts bytes to a string.

TypeValue
InputArr<Num...>an array of numbers (interpreted modulo 256 as UTF-8 bytes)
OutputStrthe string represented by the input

Examples

ProgramTypeValueError
[97, 98, 99] bytesToStrStr"abc"
[75, 195, 182, 108, 110] bytesToStrStr"Köln"
[230, 151, 165, 230, 156, 172, 232, 170, 158] bytesToStrStr"日本語"
[0] bytesToStrStr"\x00"
[256] bytesToStrStr"\x00"

codePoints

Converts a string to Unicode code points.

TypeValue
InputStra string
OutputArr<Num...>the input represented as a sequence of code points

If the input string contains invalid UTF-8 byte sequences, they will be represented by the Unicode replacement character (code point 65533).

Examples

ProgramTypeValueError
"abc" codePointsArr<Num...>[97, 98, 99]
"Köln" codePointsArr<Num...>[75, 246, 108, 110]
"日本語" codePointsArr<Num...>[26085, 26412, 35486]
"\x80" codePointsArr<Num...>[65533]

codePointsToStr

Converts Unicode code points to a string.

TypeValue
InputArr<Num...>a sequence of numbers
OutputStrUTF-8 encoded version of the input

Examples

ProgramTypeValueError
[97, 98, 99] codePointsToStrStr"abc"
[75, 246, 108, 110] codePointsToStrStr"Köln"
[26085, 26412, 35486] codePointsToStrStr"日本語"
[65533] codePointsToStrStr"�"

fields

Splits a string around whitespace.

TypeValue
InputStra string
OutputArr<Str...>the result of splitting the string around any kind or amount of white space

Examples

ProgramTypeValueError
" foo bar baz " fieldsArr<Str...>["foo", "bar", "baz"]

indexOf

Finds the position of a string within another.

TypeValue
InputStrstring to search inside
needle (param #1)Strstring to search for
OutputNumoffset of first occurrence of needle from the beginning of the input, measured in bytes, or -1 if none

Examples

ProgramTypeValueError
"abc" indexOf("bc")Num1
"abc" indexOf("a")Num0
"abc" indexOf("d")Num-1
"Köln" indexOf("l")Num3

join

Concatenates any number of strings.

TypeValue
InputArr<Str...>an array of strings
OutputStrthe concatenation of all the strings in the input

Examples

ProgramTypeValueError
["ab", "cd", "ef"] joinStr"abcdef"
["ab", "cd"] joinStr"abcd"
["ab"] joinStr"ab"
for Any def f Arr<Str...> as [] ok f joinStr""

join

Concatenates any number of strings with a custom delimiter.

TypeValue
InputArr<Str...>an array of strings
glue (param #1)Strdelimiter to put between strings
OutputStrthe concatenation of all the strings in the input, with the glue in between

Examples

ProgramTypeValueError
["ab", "cd", "ef"] join(";")Str"ab;cd;ef"
["ab", "", "cd"] join(";")Str"ab;;cd"
["ab"] join(";")Str"ab"
for Any def f Arr<Str...> as [] ok f join(";")Str""

padEnd

Right-pads a string.

TypeValue
InputStra string
targetLength (param #1)Numminimum string length for the output
padString (param #2)Strstring to use as padding to bring the input to the desired length
OutputStrthe input followed by as many repetitions of padString as necessary to reach targetLength

padString is usually one character but can be longer, in which case each repetition starts from the left.

Examples

ProgramTypeValueError
"z" padEnd(2, " ")Str"z "
"z" padEnd(3, " ")Str"z "
"zzz" padEnd(3, " ")Str"zzz"
"zzzz" padEnd(3, " ")Str"zzzz"
"zzzz" padEnd(7, "ab")Str"zzzzaba"

padStart

Left-pads a string.

TypeValue
InputStra string
targetLength (param #1)Numminimum string length for the output
padString (param #2)Strstring to use as padding to bring the input to the desired length
OutputStrthe input following as many repetitions of padString as necessary to reach targetLength

padString is usually one character but can be longer, in which case each repetition starts from the left.

Examples

ProgramTypeValueError
"z" padStart(2, " ")Str" z"
"z" padStart(3, " ")Str" z"
"zzz" padStart(3, " ")Str"zzz"
"zzzz" padStart(3, " ")Str"zzzz"
"zzzz" padStart(7, "ab")Str"abazzzz"

replaceAll

Replaces substrings.

TypeValue
InputStra string
needle (param #1)Stra substring to look for
replacement (param #2)Stra new string to replace needle with
OutputStrthe input with all occurrences of needle replaced with replacement

More precisely, whenever there are two or more overlapping occurrences of needle in the input, only the first one is replaced.

Examples

ProgramTypeValueError
"ababa" replaceAll("b", "c")Str"acaca"

replaceFirst

Replaces a substring.

TypeValue
InputStra string
needle (param #1)Stra substring to look for
replacement (param #2)Stra new string to replace needle with
OutputStrthe input with the first ocurrence of needle replaced with replacement

Examples

ProgramTypeValueError
"ababa" replaceFirst("b", "c")Str"acaba"

startsWith

Checks whether a string starts with a specific substring.

TypeValue
InputStra string
needle (param #1)Stra prefix to look for
OutputBooltrue if the input starts with needle, false otherwise

Examples

ProgramTypeValueError
"abc" startsWith("ab")Booltrue
"abc" startsWith("b")Boolfalse

endsWith

Checks whether a string ends with a specific substring.

TypeValue
InputStra string
needle (param #1)Stra suffix to look for
OutputBooltrue if the input ends with needle, false otherwise

Examples

ProgramTypeValueError
"abc" endsWith("bc")Booltrue
"abc" endsWith("b")Boolfalse

repeat

Concatenates multiple repetitions of a string.

TypeValue
InputStra string
n (param #1)Numnumber of repetitions (will be truncated and min'd to 0)
OutputStrthe input, repeated n times

Examples

ProgramTypeValueError
"abc" repeat(3)Str"abcabcabc"
"abc" repeat(0)Str""
"abc" repeat(-1)Str""
"abc" repeat(1.6)Str"abc"

slice

Extracts a substring from a string.

TypeValue
InputStra string
start (param #1)Numa positive integer
OutputStrthe portion of the input that is after offset start

Examples

ProgramTypeValueError
"abc" slice(-4)Str"abc"
"abc" slice(-3)Str"abc"
"abc" slice(-2)Str"bc"
"abc" slice(-1)Str"c"
"abc" slice(0)Str"abc"
"abc" slice(1)Str"bc"
"abc" slice(2)Str"c"
"abc" slice(3)Str""
"abc" slice(4)Str""

slice

Extracts a substring from a string.

TypeValue
InputStra string
start (param #1)Numoffset to start after
end (param #2)Numoffset to end before
OutputStrthe portion of the input that is after offset start but before offset end

Negative offsets are counted from the end of the string.

Examples

ProgramTypeValueError
"abc" slice(1, 2)Str"b"
"abc" slice(1, -1)Str"b"
"abc" slice(-2, -1)Str"b"
"abc" slice(-1, -2)Str""
"abc" slice(2, 1)Str""
"abc" slice(-5, -4)Str""
"abc" slice(-5, -3)Str""
"abc" slice(-5, -2)Str"a"
"abc" slice(-5, -1)Str"ab"
"abc" slice(-1, -5)Str""
"abc" slice(2, -5)Str""
"abc" slice(0, 4)Str"abc"
"abc" slice(4, 4)Str""

trim

Removes whitespace from the start and end of a string.

TypeValue
InputStra string
OutputStrthe input, with leading and trailing whitespace removed

Examples

ProgramTypeValueError
" abc " trimStr"abc"

trimStart

Removes whitespace from the start of a string.

TypeValue
InputStra string
OutputStrthe input, with leading whitespace removed

Examples

ProgramTypeValueError
" abc " trimStartStr"abc "

trimEnd

Removes whitespace from the end of a string.

TypeValue
InputStra string
OutputStrthe input, with trailing whitespace removed

Examples

ProgramTypeValueError
" abc " trimEndStr" abc"

Array Funcers

+

Concatenates two arrays.

TypeValue
InputArr<<A Any>...>an array
other (param #1)Arr<<B Any>...>another array
OutputArr<<A Any>|<B Any>...>the concatenation of both arrays

Examples

ProgramTypeValueError
[1, 2, 3] +[4, 5]Arr<Num...>[1, 2, 3, 4, 5]
[] +[4, 5]Arr<Num...>[4, 5]
[1, 2, 3] +[]Arr<Num...>[1, 2, 3]
[] +[]Arr<>[]
["a", "b"] +["c", "d"]Arr<Str...>["a", "b", "c", "d"]
["a", "b"] +[1, 2]Arr<Str|Num...>["a", "b", 1, 2]

all

Checks if all elements are true.

TypeValue
InputArr<Bool...>an array of boolean values
OutputBooltrue iff all elements of the input are true

Examples

ProgramTypeValueError
[] allBooltrue
[true] allBooltrue
[true, true] allBooltrue
[true, false, true] allBoolfalse

drop

Removes the first n elements from the beginning of an array.

TypeValue
InputArr<<A Any>...>an array
n (param #1)Numnumber of elements to remove
OutputArr<<A Any>...>the input with the first n elements removed

Examples

ProgramTypeValueError
[1, 2, 3] drop(-1)Arr<Num...>[1, 2, 3]
[1, 2, 3] drop(0)Arr<Num...>[1, 2, 3]
[1, 2, 3] drop(1)Arr<Num...>[2, 3]
[1, 2, 3] drop(2)Arr<Num...>[3]
[1, 2, 3] drop(3)Arr<Num...>[]
[1, 2, 3] drop(4)Arr<Num...>[]

dropWhile

Removes elements satisfying a predicate from the beginning of an array.

TypeValue
InputArr<<A Any>...>an array
predicate (param #1)for <A Any> Obj<yes: <B Any>, Any>|Obj<no: <C Any>, Any>a predicate to apply to the elements of the input
OutputArr<<A Any>...>The elements from the input, starting with the first one that does not satisfy the predicate.

Examples

ProgramTypeValueError
[{a: 1}, {a: 2}, {b: 3}, {a: 4}] dropWhile(is {a: _})Arr<Obj<b: Num, Void>|Obj<a: Num, Void>...>[{b: 3}, {a: 4}]

each

Applies a function to every element.

TypeValue
InputArr<<A Any>...>an array
f (param #1)for <A Any> <B Any>a function to apply to each element of the input
OutputArr<<B Any>...>a list with the outputs of f applied to each element of the input

Examples

ProgramTypeValueError
[1, 2, 3] each(*2)Arr<Num...>[2, 4, 6]
[{a: 1}, {a: 2}, {b: 3}, {a: 4}] takeWhile(is {a: _}) each(@a)Arr<Num...>[1, 2]

enum

Pairs each element with a 0-based index.

TypeValue
InputArr<<A Any>...>
OutputArr<Arr<Num, <A Any>>...>the input with each element replaced with a 2-element array, the second element of which is the original element and the first is its index in the array, counting from 0

Examples

ProgramTypeValueError
["a", "b", "c"] enumArr<Arr<Num, Str>...>[[0, "a"], [1, "b"], [2, "c"]]

enum

Pairs each element with an index.

TypeValue
InputArr<<A Any>...>an array
start (param #1)Numat which number to start counting
OutputArr<Arr<Num, <A Any>>...>the input with each element replaced with a 2-element array, the second element of which is the original element and the first is its index in the array, counting from start

Examples

ProgramTypeValueError
["a", "b", "c"] enum(1)Arr<Arr<Num, Str>...>[[1, "a"], [2, "b"], [3, "c"]]

findFirst

Finds the index and first element satisfying a predicate.

TypeValue
InputArr<<A Any>...>an array
predicate (param #1)for <A Any> Obj<yes: <B Any>, Any>|Obj<no: <C Any>, Any>a predicate to apply to elements of the input
OutputNull|Arr<Num, <A Any>>the first element of the input satisfying the predicate, paired with its index, or Null if none

Examples

ProgramTypeValueError
[1, 2, 3] findFirst(is Num with %2 ==0)Null|Arr<Num, Num>[1, 2]
[1, 2, 3] findFirst(is Num with %4 ==0)Null|Arr<Num, Num>null

findFirstIndex

Finds the index of the first element satisfying a predicate.

TypeValue
InputArr<<A Any>...>an array
predicate (param #1)for <A Any> Obj<yes: <B Any>, Any>|Obj<no: <C Any>, Any>a predicate to apply to elements of the input
OutputNull|Numthe index of the first element of the input satisfying the predicate, or Null if none

Examples

ProgramTypeValueError
[1, 2, 3] findFirstIndex(is Num with %2 ==0)Null|Num1
[1, 2, 3] findFirstIndex(is Num with %4 ==0)Null|Numnull

findFirstValue

Finds the first element satisfying a predicate.

TypeValue
InputArr<<A Any>...>an array
predicate (param #1)for <A Any> Obj<yes: <B Any>, Any>|Obj<no: <C Any>, Any>a predicate to apply to elements of the input
OutputNull|<A Any>the first element of the input satisfying the predicate, or Null if none

Examples

ProgramTypeValueError
[1, 2, 3] findFirstValue(is Num with %2 ==0)Null|Num2
[1, 2, 3] findFirstValue(is Num with %4 ==0)Null|Numnull

findLast

Finds the index and last element satisfying a predicate.

TypeValue
InputArr<<A Any>...>an array
predicate (param #1)for <A Any> Obj<yes: <B Any>, Any>|Obj<no: <C Any>, Any>a predicate to apply to elements of the input
OutputNull|Arr<Num, <A Any>>the last element of the input satisfying the predicate, paired with its index, or Null if none

Examples

ProgramTypeValueError
[1, 2, 3, 4] findLast(is Num with %2 ==0)Null|Arr<Num, Num>[3, 4]
[1, 2, 3, 4] findLast(is Num with %8 ==0)Null|Arr<Num, Num>null

findLastIndex

Finds the index of the last element satisfying a predicate.

TypeValue
InputArr<<A Any>...>an array
predicate (param #1)for <A Any> Obj<yes: <B Any>, Any>|Obj<no: <C Any>, Any>a predicate to apply to elements of the input
OutputNull|Numthe index of the last element of the input satisfying the predicate, or Null if none

Examples

ProgramTypeValueError
[1, 2, 3, 4] findLastIndex(is Num with %2 ==0)Null|Num3
[1, 2, 3, 4] findLastIndex(is Num with %8 ==0)Null|Numnull

findLastValue

Finds the last element satisfying a predicate.

TypeValue
InputArr<<A Any>...>an array
predicate (param #1)for <A Any> Obj<yes: <B Any>, Any>|Obj<no: <C Any>, Any>a predicate to apply to elements of the input
OutputNull|<A Any>the last element of the input satisfying the predicate, or Null if none

Examples

ProgramTypeValueError
[1, 2, 3, 4] findLastValue(is Num with %2 ==0)Null|Num4
[1, 2, 3, 4] findLastValue(is Num with %8 ==0)Null|Numnull

fold

Aggregates an array recursively.

TypeValue
InputArr<<A Any>...>an array
start (param #1)<B Any>initial accumulator
combine (param #2)for <B Any> (<A Any>) <B Any>a function that combines the current accumulator with the next element to produce a new accumulator
Output<B Any>the accumulator after processing all elements

Examples

ProgramTypeValueError
[2, 3, 4] fold(0, +)Num9
[2, 3, 4] fold(1, *)Num24

get

Returns the element at a given index.

TypeValue
InputArr<<A Any>...>an array
index (param #1)Numa 0-based index into the input
Output<A Any>the element at the given index

Throws BadIndex if the index is invalid or NoSuchIndex if there is not element at the give index.

Examples

ProgramTypeValueError
[] get(0)VoidType error
Code: VoidProgram
Message: Type of program cannot be Void.
["a", "b", "c"] get(0)Str"a"
["a", "b", "c"] get(-1)StrValue error
Code: BadIndex
Message: Index must be a nonnegative integer.
Got value: -1
["a", "b", "c"] get(2)Str"c"
["a", "b", "c"] get(3)StrValue error
Code: NoSuchIndex
Message: Array is not long enough.
Got value: 3

get

Returns the element at a given index, or a default value.

TypeValue
InputArr<<A Any>...>an array
index (param #1)Numa 0-based index into the input
default (param #2)<B Any>default value to retur if there is no element at the given index
Output<A Any>|<B Any>the element at the given index, or default if there isn't one.

Throws BadIndex if the index is invalid.

Examples

ProgramTypeValueError
[] get(0, null)Nullnull
["a", "b", "c"] get(0, null)Str|Null"a"
["a", "b", "c"] get(-1, null)Str|NullValue error
Code: BadIndex
Message: Index must be a nonnegative integer.
Got value: -1
["a", "b", "c"] get(3, null)Str|Nullnull

join

Join several arrays together into one.

TypeValue
InputArr<Arr<<A Any>...>...>an array of arrays
OutputArr<<A Any>...>All arrays in the input joined together into one.

Examples

ProgramTypeValueError
[] joinArr<<A>...>[]
[[]] joinArr<>[]
[[1]] joinArr<Num...>[1]
[[1, 2]] joinArr<Num...>[1, 2]
[[], []] joinArr<>[]
[[], [1]] joinArr<Num...>[1]
[[1], [2, 3]] joinArr<Num...>[1, 2, 3]
[[1], [2, [3]]] joinArr<Num|Arr<Num>...>[1, 2, [3]]

keep

Keep only elements satisfying a predicate.

TypeValue
InputArr<<A Any>...>an array
predicate (param #1)for <A Any> Obj<yes: <B Any>, Any>|Obj<no: <C Any>, Any>a predicate to apply to elements of the input
OutputArr<<B Any>...>The input with all elements not satisfying the predicate removed.

Examples

ProgramTypeValueError
["a", 1, "b", 2, "c", 3] keep(is Num with %2 >0 elis Str)Arr<Num|Str...>["a", 1, "b", "c", 3]
[{n: 1}, {n: 2}, {n: 3}] keep(is {n: n} with n %2 >0)Arr<Obj<n: Num, Void>...>[{n: 1}, {n: 3}]
[1, 2, 3, 4, 5, 6] keep(if %2 ==0) each(*2)Arr<Num...>[4, 8, 12]
[1, 2, 3, 4, 5, 6] keep(if %2 ==0 not) each(id)Arr<Num...>[1, 3, 5]
[1, 2, 3] keep(if %2 ==0 not) each(+1)Arr<Num...>[2, 4]
[1, 2, 3] keep(if false)Arr<Num...>[]
[{n: 1}, 2, {n: 3}] keep(is {n: n}) each(@n)Arr<Num...>[1, 3]

len

Computes the length of an array.

TypeValue
InputArr<Any...>an array
OutputNumhow many elements the input has

Examples

ProgramTypeValueError
[] lenNum0
["a", 2, []] lenNum3

max

Finds the maximum element.

TypeValue
InputArr<<A Any>...>an array
less (param #1)for <A Any> (<A Any>) Boolfuncer that tests whether its input is "less than" its first argument
default (param #2)<B Any>default value to return if the input is empty
Output<A Any>|<B Any>the maximum element, or default if the input is empty

Examples

ProgramTypeValueError
["abc", "b", "ab"] max(<, "")Str"b"
[0, 1, 2] max(>, -100)Num0
for Any def f Arr<Num...> as [] ok f max(<, 0)Num0

max

Finds the maximum element according to a sorting key.

TypeValue
InputArr<<A Any>...>an array
sortKey (param #1)for <A Any> <B Any>funcer that maps input elements to values by which they will be compared
less (param #2)for <B Any> (<B Any>) Boolfuncer that tests whether its input is "less than" its first argument
default (param #3)<C Any>default value to return if the input is empty
Output<A Any>|<C Any>the maximum element, or default if the input is empty

Examples

ProgramTypeValueError
["abc", "b", "ab"] max(bytes len, <, "")Str"abc"

min

Finds the minimum element.

TypeValue
InputArr<<A Any>...>an array
less (param #1)for <A Any> (<A Any>) Boolfuncer that tests whether its input is "less than" its first argument
default (param #2)<B Any>default value to return if the input is empty
Output<A Any>|<B Any>the minimum element, or default if the input is empty

Examples

ProgramTypeValueError
["abc", "b", "ab"] min(<, "")Str"ab"

min

Finds the minimum element according to a sorting key.

TypeValue
InputArr<<A Any>...>an array
sortKey (param #1)for <A Any> <B Any>funcer that maps input elements to values by which they will be compared
less (param #2)for <B Any> (<B Any>) Boolfuncer that tests whether its input is "less than" its first argument
default (param #3)<C Any>default value to return if the input is empty
Output<A Any>|<C Any>the minimum element, or default if the input is empty

Examples

ProgramTypeValueError
["abc", "b", "ab"] min(bytes len, <, "")Str"b"

range

Builds a range of numbers

TypeValue
InputAnyany value (is ignored)
from (param #1)Numlower limit (inclusive)
to (param #2)Numupper limit (inclusive)
OutputArr<Num...>an array with the integers in the specified interval

Examples

ProgramTypeValueError
range(0, 4)Arr<Num...>[0, 1, 2, 3]
range(-1, 2)Arr<Num...>[-1, 0, 1]
range(3, 2)Arr<Num...>[]

repeat

Concatenates an array with copies of itself.

TypeValue
InputArr<<A Any>...>an array
times (param #1)Numhow many times to repeat the input
OutputArr<<A Any>...>the elements of the input repeated times times in a single array

Examples

ProgramTypeValueError
[1, 2, 3] repeat(3)Arr<Num...>[1, 2, 3, 1, 2, 3, 1, 2, 3]
[1, 2, 3] repeat(0)Arr<Num...>[]
[1, 2, 3] repeat(1)Arr<Num...>[1, 2, 3]

rev

Reverses an array.

TypeValue
InputArr<<A Any>...>an array
OutputArr<<A Any>...>the input in reverse order

Examples

ProgramTypeValueError
[1, 2, 3] revArr<Num...>[3, 2, 1]
[] revArr<>[]

some

Checks if some element is true.

TypeValue
InputArr<Bool...>an array of boolean values
OutputBooltrue iff at least one element of the input is true

Examples

ProgramTypeValueError
[] someBoolfalse
[false] someBoolfalse
[false, false] someBoolfalse
[false, true, false] someBooltrue

sort

Sorts numbers.

TypeValue
InputArr<Num...>an array of numbers
OutputArr<Num...>the input sorted from smallest to greatest

Examples

ProgramTypeValueError
[7, 3, 2, 5, 2] sortArr<Num...>[2, 2, 3, 5, 7]

sort

Sorts strings.

TypeValue
InputArr<Str...>an array of strings
OutputArr<Str...>the input sorted lexicographically

Examples

ProgramTypeValueError
"Zwölf Boxkämpfer jagen Victor quer über den großen Sylter Deich . Voilà !" fields sortArr<Str...>["!", ".", "Boxkämpfer", "Deich", "Sylter", "Victor", "Voilà", "Zwölf", "den", "großen", "jagen", "quer", "über"]

sort

Sorts values.

TypeValue
InputArr<<A Any>...>an array
less (param #1)for <A Any> (<A Any>) Boolfuncer that tests whether its input is "less than" its first argument
OutputArr<<A Any>...>the input sorted by the given ordering function

Examples

ProgramTypeValueError
[7, 3, 2, 5] sort(>)Arr<Num...>[7, 5, 3, 2]
"Zwölf Boxkämpfer jagen Victor quer über den großen Sylter Deich . Voilà !" fields sort(>)Arr<Str...>["über", "quer", "jagen", "großen", "den", "Zwölf", "Voilà", "Victor", "Sylter", "Deich", "Boxkämpfer", ".", "!"]
[{a: 7}, {a: 3}, {a: 2}, {a: 5}] for Obj<a: Num, Void> def <(other Obj<a: Num, Void>) Bool as @a <(other @a) ok sort(<)Arr<Obj<a: Num, Void>...>[{a: 2}, {a: 3}, {a: 5}, {a: 7}]
[{a: 7, b: 2}, {a: 3, b: 1}, {a: 2, b: 2}, {a: 5, b: 2}] for Obj<a: Num, b: Num, Void> def <(other Obj<a: Num, b: Num, Void>) Bool as @b <(other @b) ok sort(<)Arr<Obj<a: Num, b: Num, Void>...>[{a: 3, b: 1}, {a: 7, b: 2}, {a: 2, b: 2}, {a: 5, b: 2}]

sortBy

Sorts an array with a sorting key.

TypeValue
InputArr<<A Any>...>an array
sortKey (param #1)for <A Any> <B Any>funcer that maps input elements to values by which they will be compared
less (param #2)for <B Any> (<B Any>) Boolfuncer that tests whether its input is "less than" its first argument
OutputArr<<A Any>...>the input sorting according to the given sorting key and ordering function

Examples

ProgramTypeValueError
[{a: 7}, {a: 3}, {a: 2}, {a: 5}] sortBy(@a, <)Arr<Obj<a: Num, Void>...>[{a: 2}, {a: 3}, {a: 5}, {a: 7}]
[{a: 7, b: 2}, {a: 3, b: 1}, {a: 2, b: 2}, {a: 5, b: 2}] sortBy(@b, <)Arr<Obj<a: Num, b: Num, Void>...>[{a: 3, b: 1}, {a: 7, b: 2}, {a: 2, b: 2}, {a: 5, b: 2}]

take

Takes the first n elements from an array.

TypeValue
InputArr<<A Any>...>an array
n (param #1)Numnumber of elements to take
OutputArr<<A Any>...>array with the first n elements from the input

Examples

ProgramTypeValueError
[1, 2, 3] take(2)Arr<Num...>[1, 2]
[1, 2, 3] take(1)Arr<Num...>[1]
[1, 2, 3] take(0)Arr<Num...>[]
[1, 2, 3] take(-1)Arr<Num...>[]
[1, 2, 3] take(4)Arr<Num...>[1, 2, 3]
[1, 2, 3] take(3)Arr<Num...>[1, 2, 3]

takeWhile

Takes elements from the beginning of an array that satisfy a certain predicate.

TypeValue
InputArr<<A Any>...>an array
predicate (param #1)for <A Any> Obj<yes: <B Any>, Any>|Obj<no: <C Any>, Any>a predicate to apply to elements of the input
OutputArr<<B Any>...>an array with the elements that satisfy the predicate, up to and excluding the first one that doesn't

Examples

ProgramTypeValueError
[1, 3, 5, 2, 4, 7] takeWhile(if %2 ==1)Arr<Num...>[1, 3, 5]
[1, 3, 5, 2, 4, 7] takeWhile(if %2 ==0)Arr<Num...>[]
[{a: 1}, {a: 2}, {b: 3}, {a: 4}] takeWhile(is {a: _}) each(@a)Arr<Num...>[1, 2]

Object Funcers

+

Combines the items of two objects into one.

TypeValue
InputObj<Any>an object
other (param #1)Obj<Any>another object
OutputObj<Any>an object with the items of the input and other

Where the input and other share keys, the values of other are used in the output.

Examples

ProgramTypeValueError
{a: 1} +{b: 2}Obj<>{a: 1, b: 2}
{a: 1, b: 2} +{b: 3}Obj<>{a: 1, b: 3}

get

Retrieves the value of a given property.

TypeValue
InputObj<<A Any>>an object
prop (param #1)Str|Numa property key
Output<A Any>the value associated in the input object with the given property key

Examples

ProgramTypeValueError
{} get("a")Void{"Code":"VoidProgram","Kind":"Type"}
{a: 1} get("a")Num1
{a: 1, b: "hey"} get("a")Num|Str1
{a: 1, b: "hey", c: false} get("a")Num|Str|Bool1
{1: "a"} get(1)Str"a"
{1.5: "a"} get(1.5)Str"a"
{b: 1} get("a")Num{"Code":"NoSuchProperty","GotValue":"\"a\"","Kind":"Value"}

has

Checks for the presence of a given property.

TypeValue
InputObj<<A Any>>an object
prop (param #1)Str|Numa property key
OutputBooltrue if the object has the given property, false if not

Examples

ProgramTypeValueError
{} has("a")Boolfalse
{a: 1} has("a")Booltrue

items

Iterates over the properties together with the values.

TypeValue
InputObj<<A Any>>an object
OutputArr<Arr<Str, <A Any>>...>an array of tuples of the properties and associated values of the input object

Examples

ProgramTypeValueError
{a: 1, b: 2} items sortBy(@0, <)Arr<Arr<Str, Num>...>[["a", 1], ["b", 2]]
{} itemsArr<Arr<Str, Void>...>[]

props

Lists the properties of an object.

TypeValue
InputObj<<A Any>>an object
OutputArr<Str...>all the property keys of the object, as an array

Examples

ProgramTypeValueError
{a: 1, b: 2} props sortArr<Str...>["a", "b"]
{} propsArr<Str...>[]

values

Lists the values of an object.

TypeValue
InputObj<<A Any>>an object
OutputArr<<A Any>...>all the property values of the object, as an array

Examples

ProgramTypeValueError
{a: 1, b: 2} values sortArr<Num...>[1, 2]
{} valuesArr<>[]

without

Removes a property from an object.

TypeValue
InputObj<<A Any>>an object
prop (param #1)Stra property key
OutputObj<<A Any>>the input object, but with the specified property removed

Examples

ProgramTypeValueError
{a: 1, b: 2} without("b")Obj<Num>{a: 1}
{a: 1, b: 2} without("c")Obj<Num>{a: 1, b: 2}

Type Funcers

type

Gives the type of the input expression.

TypeValue
Input<A Any>any value (is ignored)
OutputStra string representation of the type of the input expression

Examples

ProgramTypeValueError
typeStr"Null"
null typeStr"Null"
true typeStr"Bool"
1 typeStr"Num"
1.5 typeStr"Num"
"abc" typeStr"Str"
for Any def f Any as null ok f typeStr"Any"
[] typeStr"Arr<>"
["dog", "cat"] typeStr"Arr<Str, Str>"
["dog", 1] typeStr"Arr<Str, Num>"
["dog", 1, {}] typeStr"Arr<Str, Num, Obj<Void>>"
["dog", 1, {}, 2] typeStr"Arr<Str, Num, Obj<Void>, Num>"
{} typeStr"Obj<Void>"
{a: null} typeStr"Obj<a: Null, Void>"
{b: false, a: null} typeStr"Obj<a: Null, b: Bool, Void>"
{c: 0, b: false, a: null} typeStr"Obj<a: Null, b: Bool, c: Num, Void>"
{d: "", c: 0, b: false, a: null} typeStr"Obj<a: Null, b: Bool, c: Num, d: Str, Void>"
{e: [], d: "", c: 0, b: false, a: null} typeStr"Obj<a: Null, b: Bool, c: Num, d: Str, e: Arr<>, Void>"
{f: {}, e: [], d: "", c: 0, b: false, a: null} typeStr"Obj<a: Null, b: Bool, c: Num, d: Str, e: Arr<>, f: Obj<Void>, Void>"
for Num def f Num|Str as if ==1 then 1 else "abc" ok ok 1 f typeStr"Num|Str"
for Any def f Num|Str as 1 ok f typeStr"Num|Str"
for Any def f Void|Num as 1 ok f typeStr"Num"
for Any def f Num|Any as 1 ok f typeStr"Any"

Value Funcers

==

Checks two values for equality.

TypeValue
InputAnya value
other (param #1)Anyanother value
OutputBooltrue if the input is the same as other, false otherwise

Examples

ProgramTypeValueError
null ==nullBooltrue
null =={}Boolfalse
true ==trueBooltrue
true ==falseBoolfalse
true ==[]Boolfalse
1 ==1.0Booltrue
1 ==2Boolfalse
57 =="a"Boolfalse
"abc" =="abc"Booltrue
"" =="abc"Boolfalse
"" ==nullBoolfalse
[false, 1.0, "ab"] ==[false, 1, "a" +"b"]Booltrue
[] ==[11]Boolfalse
["a"] =={a: 1}Boolfalse
{a: 1, b: 2} =={b: 2, a: 1}Booltrue
{a: 1, b: 2} =={a: 2, b: 1}Boolfalse
{} ==[]Boolfalse

id

The identity function.

TypeValue
Input<A Any>any value
Output<A Any>the input value

Examples

ProgramTypeValueError
123 idNum123
"abc" idStr"abc"
false if id then 1 else fatal okNum"abc"{"Code":"UnexpectedValue","GotValue":"false","Kind":"Value"}

parseFloat

Parses the string representation of a floating-point number.

TypeValue
InputStra floating-point number in string representation
OutputNumthe corresponding Num value

Examples

ProgramTypeValueError
"4.567" parseFloatNum4.567
"4.567e3" parseFloatNum4567
"4.567abcdefgh" parseFloatNum{"Code":"UnexpectedValue","GotValue":"\"4.567abcdefgh\"","Kind":"Value"}

parseInt

Parses the string representation of an integer number.

TypeValue
InputStran integer number in string representation
base (param #1)Numthe base that the input is in
OutputNumthe corresponding Num value

Examples

ProgramTypeValueError
"123" parseInt(10)Num123
"ff" parseInt(10)Num{"Code":"UnexpectedValue","GotValue":"\"ff\"","Kind":"Value"}
"ff" parseInt(16)Num255
"0xFF" parseInt(16)Num255{"Code":"UnexpectedValue","GotValue":"\"0xFF\"","Kind":"Value"}

parseInt

Parses the string representation of a base-10 integer number.

TypeValue
InputStran integer number in base-10 string representation
OutputNumthe corresponding Num value

Examples

ProgramTypeValueError
"123" parseIntNum123
" 123 " parseIntNum123{"Code":"UnexpectedValue","GotValue":"\" 123 \"","Kind":"Value"}
"077" parseIntNum77
"1.9" parseIntNum1{"Code":"UnexpectedValue","GotValue":"\"1.9\"","Kind":"Value"}
"ff" parseIntNum16{"Code":"UnexpectedValue","GotValue":"\"ff\"","Kind":"Value"}
"xyz" parseIntNum16{"Code":"UnexpectedValue","GotValue":"\"xyz\"","Kind":"Value"}

parseJSON

TypeValue
InputStr
OutputAny

Examples

ProgramTypeValueError

toJSON

TypeValue
InputAny
OutputStr

Examples

ProgramTypeValueError

toObj

TypeValue
InputArr<Arr<Str, <A Any>>...>
OutputObj<<A Any>>

Examples

ProgramTypeValueError

toStr

TypeValue
InputAny
OutputStr

Examples

ProgramTypeValueError

Regexp Funcers

reFindAll

Finds all non-overlapping matches in a string.

TypeValue
InputStra string
regexp (param #1)for Str <A Null|Obj<0: Str, start: Num, Any>>a regexp
OutputArr<<A Any>...>array of matches

Matches appear in the output from leftmost to rightmost. Matches that overlap an earlier match (i.e., a match that starts at a lower offset or one that starts at the same offset but is found earlier by the regexp) are not included.

Examples

ProgramTypeValueError
"a" reFindAll~a+~Arr<Null|Obj<0: Str, start: Num, Void>...>[{start: 0, 0: "a"}]
"aa" reFindAll~a+~Arr<Null|Obj<0: Str, start: Num, Void>...>[{start: 0, 0: "aa"}]
"aba" reFindAll~a+~Arr<Null|Obj<0: Str, start: Num, Void>...>[{start: 0, 0: "a"}, {start: 2, 0: "a"}]

reReplaceFirst

Replaces the first match of a regexp in a string with something else.

TypeValue
InputStra string
regexp (param #1)for Str Null|Obj<0: Str, start: Num, Any>a regexp
replacement (param #2)for Obj<0: Str, start: Num, Any> Strtakes a match and returns a string
OutputStrthe input with the first match of the regexp replaced with the corresponding replacement, or unchanged if there is no match

Examples

ProgramTypeValueError
"aba" reReplaceFirst(a+, "c")Str"cba"
"abc" reReplaceFirst(d, "e")Str"abc"
"b0b" reReplaceFirst(\d+, @0 parseInt =n "a" repeat(n))Str"bb"
"b3b" reReplaceFirst(\d+, @0 parseInt =n "a" repeat(n))Str"baaab"
" a b c " reReplaceFirst([abc], "({@0})")Str" (a) b c "

reReplaceAll

Replaces all non-overlapping matches of a regexp in a string with something else.

TypeValue
InputStra string
regexp (param #1)for Str <A Null|Obj<0: Str, start: Num, Any>>a regexp
replacement (param #2)for Obj<0: Str, start: Num, Any> Strtakes a match and returns a string
OutputStrthe input with all matches of the regexp replaced with the corresponding replacement, or unchanged if there is no match

Matches are replaced from leftmost to rightmost. Matches that overlap an earlier match (i.e., a match that starts at a lower offset or one that starts at the same offset but is found earlier by the regexp) are not replaced.

Examples

ProgramTypeValueError
"aba" reReplaceAll(a+, "c")Str"cbc"
"abc" reReplaceAll(d, "e")Str"abc"
" a b c " reReplaceAll([abc], "({@0})")Str" (a) (b) (c) "

reSplit

Splits a string around a regexp.

TypeValue
InputStra string
separator (param #1)for Str Null|Obj<0: Str, start: Num, Any>a regexp
OutputArr<Str...>the parts of the input found in between occurrences of the separator

If the separator regexp matches the empty string, the input is split into its individual code points. Separators are found from leftmost to rightmost. Separators that overlap an earlier separator (i.e., a separator that starts at a lower offset or one that starts at the same offset but is found earlier by the regexp) do not lead to splits.

Examples

ProgramTypeValueError
"zabacad" reSplit~a~Arr<Str...>["z", "b", "c", "d"]
"zabaca" reSplit~a~Arr<Str...>["z", "b", "c", ""]
"abacad" reSplit~a~Arr<Str...>["", "b", "c", "d"]
"abaca" reSplit~a~Arr<Str...>["", "b", "c", ""]
"abaca" reSplit~~Arr<Str...>["a", "b", "a", "c", "a"]
"你好" reSplit~~Arr<Str...>["你", "好"]
"" reSplit~a~Arr<Str...>[""]
"" reSplit~~Arr<Str...>[]

reSplit

Splits a string around a regexp, up to a certain number of times.

TypeValue
InputStra string
separator (param #1)for Str Null|Obj<0: Str, start: Num, Any>a regexp
n (param #2)Nummaximum number of splits to make
OutputArr<Str...>the parts of the input found in between occurrences of the separator

If the separator regexp matches the empty string, the input is split into its individual code points. Separators are found from leftmost to rightmost. Separators that overlap an earlier separator (i.e., a separator that starts at a lower offset or one that starts at the same offset but is found earlier by the regexp) do not lead to splits. At most n splits are made so that the output contains at most n + 1 elements; later separator occurrences are ignored.

Examples

ProgramTypeValueError
"zabacad" reSplit(a, 1)Arr<Str...>["z", "bacad"]
"zabaca" reSplit(a, 1)Arr<Str...>["z", "baca"]
"zabaca" reSplit(a, 3)Arr<Str...>["z", "b", "c", ""]
"zabaca" reSplit(a, 4)Arr<Str...>["z", "b", "c", ""]
"abacad" reSplit(a, 1)Arr<Str...>["", "bacad"]
"abacad" reSplit(a, 2)Arr<Str...>["", "b", "cad"]
"abaca" reSplit(a, 1)Arr<Str...>["", "baca"]
"abaca" reSplit(a, 2)Arr<Str...>["", "b", "ca"]
"abaca" reSplit(a, 3)Arr<Str...>["", "b", "c", ""]
"abaca" reSplit(~~, 2)Arr<Str...>["a", "b", "aca"]
"abaca" reSplit(~~, 1000)Arr<Str...>["a", "b", "a", "c", "a"]
"你好" reSplit(~~, 0)Arr<Str...>["你好"]
"" reSplit(a, 0)Arr<Str...>[""]
"" reSplit(a, 1)Arr<Str...>[""]
"" reSplit(~~, 0)Arr<Str...>[]
"" reSplit(~~, 1)Arr<Str...>[]

Control Flow Abstraction Funcers

fatal

Aborts with an error message

TypeValue
InputAnyany value
OutputVoiddoes not return

Examples

ProgramTypeValueError
1 if ==1 then fatal else true okBool{"Code":"UnexpectedValue","GotValue":"1","Kind":"Value","Pos":"1:15"}

must

Aborts with an error message if input is null

TypeValue
InputNull|<A Any>a value that you want to be sure is not null
Output<A Any>the input value, unless it is null

Examples

ProgramTypeValueError
null mustNull{"Code":"UnexpectedValue","GotValue":"null","Kind":"Value","Pos":"1:6"}