Files
cell/docs/functions.md
2026-02-20 15:33:46 -06:00

504 lines
14 KiB
Markdown

---
title: "Built-in Functions"
description: "Intrinsic constants and functions"
weight: 60
type: "docs"
---
The intrinsics are constants and functions that are built into the language. The `use` statement is not needed to access them.
A programmer is not obliged to consult the list of intrinsics before naming a new variable or input. New intrinsics may be added to ƿit without breaking existing programs.
## Constants
### false
The value of `1 == 0`. One of the two logical values.
### true
The value of `1 == 1`. One of the two logical values.
### null
The value of `1 / 0`. The null value is an empty immutable object. All attempts to obtain a value from null by refinement will produce null.
Any attempt to modify null will disrupt. Any attempt to call null as a function will disrupt.
null is the value of missing input values, missing fields in records, and invalid numbers.
### pi
An approximation of circumference / diameter: 3.1415926535897932.
## Creator Functions
The creator functions are **polymorphic** — they examine the types of their arguments to decide what to do. The first argument's type selects the behavior. All return null if their inputs are not suitable.
### array
The `array` function creates arrays from various inputs. Its behavior depends on the type of the first argument:
**From a number** — create an array of that size:
`array(number)` — All elements are initialized to null.
`array(number, initial_value)` — All elements are initialized to initial_value. If initial_value is a function, it is called for each element. If the function has arity >= 1, it is passed the element number.
```javascript
array(3) // [null, null, null]
array(3, 0) // [0, 0, 0]
array(5, i => i * 2) // [0, 2, 4, 6, 8]
```
**From an array** — copy, map, concat, or slice:
`array(array)` — Copy. Make a mutable copy of the array.
`array(array, function, reverse, exit)` — Map. Call the function with each element, collecting return values in a new array. The function is passed each element and its element number.
```javascript
array([1, 2, 3], x => x * 10) // [10, 20, 30]
```
If reverse is true, starts with the last element and works backwards.
If exit is not null, when the function returns the exit value, array returns early. The exit value is not stored into the new array.
`array(array, another_array)` — Concat. Produce a new array concatenating both.
```javascript
array([1, 2], [3, 4]) // [1, 2, 3, 4]
```
`array(array, from, to)` — Slice. Make a mutable copy of part of an array. If from is negative, add length(array). If to is negative, add length(array).
```javascript
array([1, 2, 3, 4, 5], 1, 4) // [2, 3, 4]
array([1, 2, 3], -2) // [2, 3]
```
**From a record** — get keys:
`array(record)` — Keys. Make an array containing all text keys in the record.
```javascript
array({a: 1, b: 2}) // ["a", "b"]
```
**From text** — split into characters or substrings:
`array(text)` — Split text into an array of individual characters (grapheme clusters). This is the standard way to iterate over characters.
```javascript
array("hello") // ["h", "e", "l", "l", "o"]
array("ƿit") // ["ƿ", "i", "t"]
```
`array(text, separator)` — Split text by a separator string into an array of subtexts.
```javascript
array("a,b,c", ",") // ["a", "b", "c"]
```
`array(text, length)` — Dice text into an array of subtexts of a given length.
### logical
```javascript
logical(0) // false
logical(false) // false
logical("false") // false
logical(null) // false
logical(1) // true
logical(true) // true
logical("true") // true
```
All other values return null.
### number
The `number` function converts values to numbers. Its behavior depends on the type of the first argument:
`number(logical)` — Returns 1 or 0.
`number(number)` — Returns the number.
`number(text, radix)` — Convert text to number. Radix is 2 thru 37 (default: 10).
`number(text, format)` — Parse formatted numbers:
| Format | Radix | Separator | Decimal point |
|--------|-------|-----------|---------------|
| `""` | 10 | | .period |
| `"n"` | 10 | | .period |
| `"u"` | 10 | _underbar | .period |
| `"d"` | 10 | ,comma | .period |
| `"s"` | 10 | space | .period |
| `"v"` | 10 | .period | ,comma |
| `"l"` | 10 | locale | locale |
| `"b"` | 2 | | |
| `"o"` | 8 | | |
| `"h"` | 16 | | |
| `"j"` | auto | | |
```javascript
number("123,456,789.10", "d") // 123456789.1
number("123.456.789,10", "v") // 123456789.1
number("666", "o") // 438
number("666", "h") // 1638
```
### text
The `text` function converts values to text. Its behavior depends on the type of the first argument:
**From an array** — join elements into text:
`text(array, separator)` — Convert array to text. Elements are concatenated with the separator (default: empty text).
```javascript
text(["h", "e", "l", "l", "o"]) // "hello"
text(["a", "b", "c"], ", ") // "a, b, c"
```
**From a number** — format as text:
`text(number, radix)` — Convert number to text. Radix is 2 thru 37 (default: 10).
`text(number, format)` — Format a number as text:
**Real styles:**
| Style | Description | Separator | Decimal |
|-------|-------------|-----------|---------|
| `"e"` | Scientific | | .period |
| `"n"` | Number | | .period |
| `"s"` | Space | space | .period |
| `"u"` | Underbar | _underbar | .period |
| `"d"` | Decimal | ,comma | .period |
| `"c"` | Comma | .period | ,comma |
| `"l"` | Locale | locale | locale |
**Integer styles:**
| Style | Base | Separator |
|-------|------|-----------|
| `"i"` | 10 | _underbar |
| `"b"` | 2 | _underbar |
| `"o"` | 8 | _underbar |
| `"h"` | 16 | _underbar |
| `"t"` | 32 | _underbar |
The format text is: `separation_digit` + `style_letter` + `places_digits`
```javascript
var data = 123456789.1
text(data) // "123456789.1"
text(data, "3s4") // "123 456 789.1000"
text(data, "d2") // "123,456,789.10"
text(data, "e") // "1.234567891e8"
text(data, "i") // "123456789"
text(data, "8b") // "111_01011011_11001101_00010101"
text(data, "h") // "75BCD15"
text(12, "4b8") // "0000_1100"
```
**From text** — extract a substring:
`text(text, from, to)` — Extract a substring. If from/to are negative, add length(text).
```javascript
var my_text = "miskatonic"
text(my_text, 0, 3) // "mis"
text(my_text, 5) // "tonic"
text(my_text, -3) // "nic"
```
### record
The `record` function creates and manipulates records (objects). Its behavior depends on the type of the first argument:
**From a record** — copy, merge, or select:
`record(record)` — Copy. Make a mutable copy.
`record(record, another_record)` — Combine. Copy a record, then put all fields of another into the copy.
`record(record, array_of_keys)` — Select. New record with only the named fields.
**From an array of keys** — create a new record:
`record(array_of_keys)` — Set. New record using array as keys, each value is true.
`record(array_of_keys, value)` — Value Set. Each field value is value.
`record(array_of_keys, function)` — Functional Value Set. The function is called for each key to produce field values.
## Sensory Functions
The sensory functions always return a logical value. In ƿit, they use the `is_` prefix:
```javascript
is_array([]) // true
is_blob(blob.make()) // true
is_function(x => x) // true
is_integer(42) // true
is_logical(true) // true
is_null(null) // true
is_number(3.14) // true
is_object({}) // true (records only)
is_text("hello") // true
```
Additional type checks: `is_character`, `is_data`, `is_digit`, `is_false`, `is_fit`, `is_letter`, `is_lower`, `is_pattern`, `is_stone`, `is_true`, `is_upper`, `is_whitespace`.
## Standard Functions
### abs(number)
Absolute value. Returns null for non-numbers.
### apply(function, array)
Execute the function, passing the array elements as input values. If the array is longer than the function's arity, it disrupts.
### ceiling(number, place)
Round up. If place is 0 or null, round to the smallest integer >= number.
```javascript
ceiling(12.3775) // 13
ceiling(12.3775, -2) // 12.38
ceiling(-12.3775) // -12
```
### character(value)
If text, returns the first character. If a non-negative 32-bit integer, returns the character from that codepoint.
### codepoint(text)
Returns the codepoint number of the first character.
### ends_with(text, suffix)
Returns `true` if the text ends with the given suffix.
```javascript
ends_with("hello.ce", ".ce") // true
ends_with("hello.cm", ".ce") // false
```
### every(array, function)
Returns `true` if every element satisfies the predicate.
```javascript
every([2, 4, 6], x => x % 2 == 0) // true
every([2, 3, 6], x => x % 2 == 0) // false
```
### extract(text, pattern, from, to)
Match text to pattern. Returns a record of saved fields, or null if no match.
### fallback(requestor_array)
Returns a requestor that tries each requestor in order until one succeeds. Returns a cancel function. See [Requestors](/docs/requestors/) for usage.
### filter(array, function)
Call function for each element. When it returns true, the element is included in the new array.
```javascript
filter([0, 1.25, 2, 3.5, 4, 5.75], is_integer) // [0, 2, 4]
```
### find(array, function, reverse, from)
Call function for each element. If it returns true, return the element number. If the second argument is not a function, it is compared directly to elements. Returns null if not found.
```javascript
find([1, 2, 3], x => x > 1) // 1
find([1, 2, 3], 2) // 1
```
### floor(number, place)
Round down. If place is 0 or null, round to the greatest integer <= number.
```javascript
floor(12.3775) // 12
floor(12.3775, -2) // 12.37
floor(-12.3775) // -13
```
### for(array, function, reverse, exit)
Call function with each element and its element number. If exit is not null and the function returns the exit value, return early.
### format(text, collection, transformer)
Substitute `{key}` placeholders in text with values from a collection (array or record).
```javascript
format("{0} in {1}!", ["Malmborg", "Plano"])
// "Malmborg in Plano!"
```
### fraction(number)
Returns the fractional part of a number. See also `whole`.
### length(value)
| Value | Result |
|-------|--------|
| array | number of elements |
| blob | number of bits |
| text | number of codepoints |
| function | number of named inputs (arity) |
| record | record.length() |
| other | null |
### lower(text)
Returns text with all uppercase characters converted to lowercase.
### max(number, number)
Returns the larger of two numbers. Returns null if either is not a number.
### min(number, number)
Returns the smaller of two numbers.
### modulo(dividend, divisor)
Result is `dividend - (divisor * floor(dividend / divisor))`. Result has the sign of the divisor.
### neg(number)
Negate. Reverse the sign of a number.
### normalize(text)
Unicode normalize.
### not(logical)
Returns the opposite logical. Returns null for non-logicals.
### parallel(requestor_array, throttle, need)
Returns a requestor that starts all requestors in the array. Results are collected into an array matching the input order. Optional throttle limits concurrent requestors. Optional need specifies the minimum number of successes required. See [Requestors](/docs/requestors/) for usage.
### race(requestor_array, throttle, need)
Like parallel, but returns as soon as the needed number of results are obtained. Default need is 1. Unfinished requestors are cancelled. See [Requestors](/docs/requestors/) for usage.
### reduce(array, function, initial, reverse)
Reduce an array to a single value by applying a function to pairs of elements.
```javascript
reduce([1, 2, 3, 4, 5, 6, 7, 8, 9], (a, b) => a + b) // 45
```
### remainder(dividend, divisor)
For fit integers: `dividend - ((dividend // divisor) * divisor)`.
### replace(text, target, replacement, limit)
Return text with target replaced by replacement. Target can be text or pattern. Replacement can be text or a function.
### reverse(array)
Returns a new array with elements in the opposite order.
### round(number, place)
Round to nearest.
```javascript
round(12.3775) // 12
round(12.3775, -2) // 12.38
```
### search(text, target, from)
Search text for target. Returns character position or null.
### sequence(requestor_array)
Returns a requestor that processes each requestor in order. Each result becomes the input to the next. The last result is the final result. See [Requestors](/docs/requestors/) for usage.
### sign(number)
Returns -1, 0, or 1.
### some(array, function)
Returns `true` if any element satisfies the predicate. Stops at the first match.
```javascript
some([1, 2, 3], x => x > 2) // true
some([1, 2, 3], x => x > 5) // false
```
### sort(array, select)
Returns a new sorted array. Sort keys must be all numbers or all texts. Sort is ascending and stable.
| select type | Sort key | Description |
|-------------|----------|-------------|
| null | element itself | Simple sort |
| text | element[select] | Sort by record field |
| number | element[select] | Sort by array index |
| array | select[index] | External sort keys |
```javascript
sort(["oats", "peas", "beans", "barley"])
// ["barley", "beans", "oats", "peas"]
sort([{n: 3}, {n: 1}], "n")
// [{n: 1}, {n: 3}]
```
### starts_with(text, prefix)
Returns `true` if the text starts with the given prefix.
```javascript
starts_with("hello world", "hello") // true
starts_with("hello world", "world") // false
```
### stone(value)
Petrify the value, making it permanently immutable. The operation is deep — all nested objects and arrays are also frozen. Returns the value.
### trim(text, reject)
Remove characters from both ends. Default removes whitespace.
### trunc(number, place)
Truncate toward zero.
```javascript
trunc(12.3775) // 12
trunc(-12.3775) // -12
```
### upper(text)
Returns text with all lowercase characters converted to uppercase.
### whole(number)
Returns the whole part of a number. See also `fraction`.