Standard library reference#

Meta: alphabetical reference, not a tutorial. Each entry: signature, one-line description, one tiny example. Group by module/receiver. Cross-link to the conceptual page that introduces the API.

This page is generated from the builtin registry in pkg/dang (stdlib.go, stdlib_random.go, stdlib_regexp.go, assert.go) and from the Dang-source prelude (pkg/dang/prelude/*.dang), whose members document themselves with a docstring for the description and an @example directive holding their runnable example. Each entry's signature, one-line description, and example come straight from the builtin's definition, so the reference can't drift from the implementation — to change an entry, edit the builtin's .Doc(...) or .Example(...). Each example is a live REPL: press Run to evaluate it (and then keep typing — state carries across entries, just like the CLI).

Top-level functions#

Path a slash-separated path, normalized on construction
SemVer a strict Semantic Version 2.0.0, accepting and removing one leading lowercase v; equality includes build metadata, while compare and sortKey use version precedence
URL a URL reference, preserving its original spelling
assert asserts that the block evaluates to a truthy value, raising an AssertionError otherwise
fromJSON parses a JSON string into an opaque value that is materialized by an expected type. Deprecated: use JSON.decode instead.
fromYAML parses a YAML string into an opaque value that is materialized by an expected type. Deprecated: use YAML.decode instead.
loop repeatedly calls the block until it exits via break
print prints a value to stdout
toJSON serializes a value to a JSON string. Deprecated: use JSON.encode instead.
toString converts a value to a string: strings, enum values, and custom scalar values as-is, other values as the Dang literal they would be written as (nested strings quoted, records as {{a: 1}})
Path(raw: String!): Path!

a slash-separated path, normalized on construction

Path("a//b/../c")
SemVer(raw: String!): SemVer!

a strict Semantic Version 2.0.0, accepting and removing one leading lowercase v; equality includes build metadata, while compare and sortKey use version precedence

SemVer("v1.2.3-rc.1+build.007")
URL(raw: String!): URL!

a URL reference, preserving its original spelling

URL("https://example.com/a%20b?x=1#part")
assert(message: String = null, &block: a): n

asserts that the block evaluates to a truthy value, raising an AssertionError otherwise

assert { 1 + 1 == 2 }
fromJSON(data: String!): Decoded@deprecated => JSON.decode

parses a JSON string into an opaque value that is materialized by an expected type. Deprecated: use JSON.decode instead.

fromJSON("[1, 2, 3]") :: [Int!]!
fromYAML(data: String!): Decoded@deprecated => YAML.decode

parses a YAML string into an opaque value that is materialized by an expected type. Deprecated: use YAML.decode instead.

fromYAML("[a, b, c]") :: [String!]!
loop(&block: a): r

repeatedly calls the block until it exits via break

loop { break 42 }
print(value: a): n

prints a value to stdout

print("hello, world")
toJSON(value: a): String!@deprecated => JSON.encode

serializes a value to a JSON string. Deprecated: use JSON.encode instead.

toJSON([1, 2, 3])
toString(value: b): String!

converts a value to a string: strings, enum values, and custom scalar values as-is, other values as the Dang literal they would be written as (nested strings quoted, records as {{a: 1}})

toString(["a": [1, 2]])

print and assert return null — there is no Void type; treat the result as null. The JSON/YAML/TOML scalars and their encode/decode are covered in depth on JSON, YAML, and TOML.

String! methods#

See Strings. .length counts characters (Unicode code points), not bytes. .bytes returns raw bytes as integers from 0 to 255 (UTF-8 for valid text); String.fromBytes(bytes: [Int!]!): String! reverses it. Both preserve invalid UTF-8 exactly, like .fromBase64; String.fromBytes raises for integers outside 0–255. For example, "é".bytes == [195, 169] and String.fromBytes([195, 169]) == "é".

Regex methods take a Regexp! pattern. Backtick template strings auto-coerce to the Regexp scalar, so a pattern is usually written as `\d+` (Go regexp/syntax).

.bytes returns the string's raw bytes as integers from 0 to 255; valid text uses UTF-8, and invalid UTF-8 bytes are preserved
.center centers the string within the specified width, counted in characters (Unicode code points), by padding with spaces on both sides; an odd remainder goes on the right
.contains checks if the string contains the specified substring
.containsMatch reports whether the string contains a match for the regexp
.fromBase64 decodes a standard (padded) base64 string, returning the decoded bytes as a string
.hasPrefix checks if the string starts with the specified prefix
.hasSuffix checks if the string ends with the specified suffix
.isEmpty returns true if the string has no characters
.length returns the number of characters (Unicode code points) in the string
.match returns the first match for the pattern, or null
.matchAll returns all non-overlapping matches for the pattern
.padLeft pads the string with spaces on the left to reach the specified width, counted in characters (Unicode code points)
.padRight pads the string with spaces on the right to reach the specified width, counted in characters (Unicode code points)
.replace replaces occurrences of old with new in the string. The count parameter controls how many replacements to make: -1 (default) replaces all occurrences, 1 replaces only the first, etc.
.replaceMatches replaces matches of pattern with `with`; supports $0/$1/$name backref expansion
.rewriteMatches replaces matches of pattern using the block to compute each replacement
.split splits a string by separator
.splitMatches splits the string by matches of pattern
.toBase64 encodes the string's bytes as a standard (padded) base64 string
.toInt parses the string as an integer in the given base (2 to 36, default 10), with an optional leading + or -. Raises if the string isn't a valid integer in that base or doesn't fit in an Int.
.toLower converts a string to lowercase
.toUpper converts a string to uppercase
.trim removes all leading and trailing characters in cutset from the string
.trimLeft removes all leading characters in cutset from the string
.trimPrefix removes the specified prefix from the string if present
.trimRight removes all trailing characters in cutset from the string
.trimSpace removes all leading and trailing whitespace from the string
.trimSuffix removes the specified suffix from the string if present
.truncate truncates the string to at most the given length (in characters). If the string is already that length or shorter, it is returned unchanged. A length of zero or less yields an empty string.
.bytes: [Int!]!

returns the string's raw bytes as integers from 0 to 255; valid text uses UTF-8, and invalid UTF-8 bytes are preserved

"café".bytes
.center(width: Int!): String!

centers the string within the specified width, counted in characters (Unicode code points), by padding with spaces on both sides; an odd remainder goes on the right

"hé".center(7) + "|"
.contains(substring: String!): Boolean!

checks if the string contains the specified substring

"dang".contains("an")
.containsMatch(pattern: Regexp!): Boolean!

reports whether the string contains a match for the regexp

"abc123".containsMatch(`\d+`)
.fromBase64: String!

decodes a standard (padded) base64 string, returning the decoded bytes as a string

"aGVsbG8=".fromBase64
.hasPrefix(prefix: String!): Boolean!

checks if the string starts with the specified prefix

"dang".hasPrefix("da")
.hasSuffix(suffix: String!): Boolean!

checks if the string ends with the specified suffix

"dang".hasSuffix("ng")
.isEmpty: Boolean!

returns true if the string has no characters

"".isEmpty
.length: Int!

returns the number of characters (Unicode code points) in the string

"héllo".length
.match(pattern: Regexp!): Match

returns the first match for the pattern, or null

"x42y".match(`\d+`)
.matchAll(pattern: Regexp!): [Match!]!

returns all non-overlapping matches for the pattern

"a1 b22 c333".matchAll(`\d+`)
.padLeft(width: Int!): String!

pads the string with spaces on the left to reach the specified width, counted in characters (Unicode code points)

"hé".padLeft(5) + "|"
.padRight(width: Int!): String!

pads the string with spaces on the right to reach the specified width, counted in characters (Unicode code points)

"hé".padRight(5) + "|"
.replace(old: String!, new: String!, count: Int = -1): String!

replaces occurrences of old with new in the string. The count parameter controls how many replacements to make: -1 (default) replaces all occurrences, 1 replaces only the first, etc.

"a-b-c".replace("-", "_")
.replaceMatches(pattern: Regexp!, with: String!, count: Int = -1): String!

replaces matches of pattern with `with`; supports $0/$1/$name backref expansion

"a1b2".replaceMatches(`\d`, "#")
.rewriteMatches(pattern: Regexp!, count: Int = -1, &block(match: Match!): String!): String!

replaces matches of pattern using the block to compute each replacement

"hello world".rewriteMatches(`\w+`) { m => m.string.toUpper }
.split(separator: String!, limit: Int = 0): [String!]!

splits a string by separator

"a,b,c".split(",")
.splitMatches(pattern: Regexp!, limit: Int = 0): [String!]!

splits the string by matches of pattern

"a1b22c".splitMatches(`\d+`)
.toBase64: String!

encodes the string's bytes as a standard (padded) base64 string

"hello".toBase64
.toInt(base: Int = 10): Int!

parses the string as an integer in the given base (2 to 36, default 10), with an optional leading + or -. Raises if the string isn't a valid integer in that base or doesn't fit in an Int.

"ff".toInt(base: 16)
.toLower: String!

converts a string to lowercase

"HELLO".toLower
.toUpper: String!

converts a string to uppercase

"hello".toUpper
.trim(cutset: String!): String!

removes all leading and trailing characters in cutset from the string

"__hi__".trim("_")
.trimLeft(cutset: String!): String!

removes all leading characters in cutset from the string

"__hi__".trimLeft("_")
.trimPrefix(prefix: String!): String!

removes the specified prefix from the string if present

"v1.2.3".trimPrefix("v")
.trimRight(cutset: String!): String!

removes all trailing characters in cutset from the string

"__hi__".trimRight("_")
.trimSpace: String!

removes all leading and trailing whitespace from the string

"  hi  ".trimSpace
.trimSuffix(suffix: String!): String!

removes the specified suffix from the string if present

"report.txt".trimSuffix(".txt")
.truncate(length: Int!): String!

truncates the string to at most the given length (in characters). If the string is already that length or shorter, it is returned unchanged. A length of zero or less yields an empty string.

"hello world".truncate(5)
String.fromBytes(bytes: [Int!]!): String!

constructs a string from raw bytes, preserving them exactly, including invalid UTF-8; raises if any integer is outside 0 to 255

String.fromBytes([99, 97, 102, 195, 169])

Path! methods#

Path is a slash-separated path scalar, normalized on construction — Path("a//b/../c") is Path("a/c"), so there is no clean. Construct with the Path(...) function (any String), a string literal in a Path!-typed slot, or :: Path!. A Path value degrades back to String! at value-handoff boundaries (call args, typed slots, returns), so it can be passed anywhere a plain path string is expected. Path is defined in Dang itself — the interpreter's embedded prelude — as a scalar with a body of methods and a new() normalization hook.

.ascend yields the path and each of its ancestors, from the path up to its root, and returns them in order; a relative path bottoms out at its first segment rather than yielding `.`
.contains whether other is the same path or lexically contained within it; mixing absolute and relative paths is never containment
.descend yields the path's ancestors and the path itself, from the root down, and returns them in order; the mirror of `ascend`
.extension the extension of the last path element without its dot, or null when there is none; a leading dot alone (".bashrc") does not begin an extension
.isAbsolute whether the path is absolute
.isRoot whether the path is the filesystem root `/`
.join the path extended with another path, normalized
.matches whether the path matches the shell-style glob pattern; raises when the pattern is invalid
.name the last element of the path
.parent the path with its last element removed; the parent of the root is the root, and the parent of a bare name is `.`
.parts the path's segments, excluding the root; the empty path `.` has none
.relativeTo the path expressed relative to base, or null when that is not expressible (mixing absolute and relative paths, or base escaping upward through `..`)
.stem the last element of the path with its extension removed
.string the path as a plain String
.ascend(&block(dir: Path!): r): [Path!]!

yields the path and each of its ancestors, from the path up to its root, and returns them in order; a relative path bottoms out at its first segment rather than yielding `.`

Path("/usr/local/bin").ascend { dir => print(dir) }
.contains(other: Path!): Boolean!

whether other is the same path or lexically contained within it; mixing absolute and relative paths is never containment

Path("/usr/local").contains("/usr/local/bin")
.descend(&block(dir: Path!): r): [Path!]!

yields the path's ancestors and the path itself, from the root down, and returns them in order; the mirror of `ascend`

Path("/usr/local/bin").descend { dir => print(dir) }
.extension: String

the extension of the last path element without its dot, or null when there is none; a leading dot alone (".bashrc") does not begin an extension

Path("src/app.tar.gz").extension
.isAbsolute: Boolean!

whether the path is absolute

Path("/etc").isAbsolute
.isRoot: Boolean!

whether the path is the filesystem root `/`

Path("/").isRoot
.join(other: Path!): Path!

the path extended with another path, normalized

Path("a").join("b/c")
.matches(pattern: String!): Boolean!

whether the path matches the shell-style glob pattern; raises when the pattern is invalid

Path("main.dang").matches("*.dang")
.name: String!

the last element of the path

Path("/usr/local/bin").name
.parent: Path!

the path with its last element removed; the parent of the root is the root, and the parent of a bare name is `.`

Path("/usr/local/bin").parent
.parts: [String!]!

the path's segments, excluding the root; the empty path `.` has none

Path("/usr/local/bin").parts
.relativeTo(base: Path!): Path

the path expressed relative to base, or null when that is not expressible (mixing absolute and relative paths, or base escaping upward through `..`)

Path("/usr/local/bin").relativeTo("/usr")
.stem: String!

the last element of the path with its extension removed

Path("src/app.tar.gz").stem
.string: String!

the path as a plain String

Path("a//b/./c").string

SemVer! methods#

SemVer("v1.2.3-rc.1+build.7") validates a SemVer 2.0.0 version and removes an optional leading v. All three core numbers are required.

Build metadata affects equality, but not version precedence. Use .compare or .sortBy { version => version.sortKey } for semantic ordering; ordinary scalar ordering and .sort compare the text instead.

let releases: [SemVer!]! = ["v1.10.0", "1.2.0", "1.2.0-rc.1"]
releases.sortBy { version => version.sortKey }.map { version => version.string }
=> ["1.2.0-rc.1", "1.2.0", "1.10.0"]
.build build metadata without the leading plus, or null when absent
.bumpMajor increment major, reset minor and patch to zero, and remove both suffixes
.bumpMinor increment minor, reset patch to zero, and remove both suffixes
.bumpPatch increment patch and remove both suffixes
.compare compare version precedence, ignoring build metadata; returns -1, 0, or 1
.core the version without prerelease or build metadata
.isPrerelease whether the version has prerelease identifiers
.major the major version as an Int; raises when it exceeds Int's range
.minor the minor version as an Int; raises when it exceeds Int's range
.patch the patch version as an Int; raises when it exceeds Int's range
.prerelease prerelease identifiers without the leading hyphen, or null when absent
.sortKey a list key for SemVer precedence with sortBy, ignoring build metadata; ordinary scalar comparison and sort still order version text lexically
.string canonical version text, without a leading v and preserving identifier case
.withBuild replace build metadata, preserving prerelease identifiers; null removes it, while empty or invalid identifiers raise an error
.withPrerelease replace prerelease identifiers, preserving build metadata; null removes them, while empty or invalid identifiers raise an error
.build: String

build metadata without the leading plus, or null when absent

SemVer("1.2.3+build.007").build
.bumpMajor: SemVer!

increment major, reset minor and patch to zero, and remove both suffixes

SemVer("1.2.3-rc.1+build.7").bumpMajor
.bumpMinor: SemVer!

increment minor, reset patch to zero, and remove both suffixes

SemVer("1.2.3-rc.1+build.7").bumpMinor
.bumpPatch: SemVer!

increment patch and remove both suffixes

SemVer("1.2.3-rc.1+build.7").bumpPatch
.compare(other: SemVer!): Int!

compare version precedence, ignoring build metadata; returns -1, 0, or 1

SemVer("1.2.3-rc.1").compare("1.2.3")
.core: SemVer!

the version without prerelease or build metadata

SemVer("1.2.3-rc.1+build.7").core
.isPrerelease: Boolean!

whether the version has prerelease identifiers

SemVer("1.2.3-rc.1").isPrerelease
.major: Int!

the major version as an Int; raises when it exceeds Int's range

SemVer("1.2.3").major
.minor: Int!

the minor version as an Int; raises when it exceeds Int's range

SemVer("1.2.3").minor
.patch: Int!

the patch version as an Int; raises when it exceeds Int's range

SemVer("1.2.3").patch
.prerelease: String

prerelease identifiers without the leading hyphen, or null when absent

SemVer("1.2.3-rc.1").prerelease
.sortKey: [String!]!

a list key for SemVer precedence with sortBy, ignoring build metadata; ordinary scalar comparison and sort still order version text lexically

[SemVer("1.10.0"), SemVer("1.2.0")].sortBy { v => v.sortKey }
.string: String!

canonical version text, without a leading v and preserving identifier case

SemVer("v1.2.3-RC.1+Build.007").string
.withBuild(build: String): SemVer!

replace build metadata, preserving prerelease identifiers; null removes it, while empty or invalid identifiers raise an error

SemVer("1.2.3-rc.1").withBuild("build.007")
.withPrerelease(prerelease: String): SemVer!

replace prerelease identifiers, preserving build metadata; null removes them, while empty or invalid identifiers raise an error

SemVer("1.2.3+build.7").withPrerelease("rc.1")

URL! methods#

URL(raw: String!) accepts absolute URLs and relative references, preserving the original text. .path and .fragment expose decoded text; .escapedPath and .rawQuery retain escaping. .query groups repeated parameters into lists and returns an empty map when there is no query.

URL paths are strings, not filesystem paths: repeated and trailing slashes can matter. An existing Path works with .withPath, and its .parts work with .appendPath. Use Path(url.path) when you explicitly want path normalization.

Building URLs#

Start from a base URL or build one from components. Helpers return a new URL and escape decoded data for you. .appendPath adds segments as data; .resolve follows references such as ../other instead.

let endpoint = URL("")
  .withScheme("https")
  .withHostname("api.example.com")
  .withPort(8443)
  .withPath(Path("/api"))
  .appendPath(["users", "name/with/slashes"])
  .withQuery(["tag": ["a", "b"]])
  .withAddedQueryParam("tag", "c")
  .withFragment("details")
endpoint.string
=> "https://api.example.com:8443/api/users/name%2Fwith%2Fslashes?tag=a&tag=b&tag=c#details"

Methods#

.appendPath append decoded path segments as data, escaping embedded slashes and literal . or .. segments rather than treating them as navigation
.escapedPath the escaped path, preserving valid original escapes
.fragment the decoded fragment without #, null when absent and empty for an explicit #
.host the host with explicit port and IPv6 brackets, excluding user information; null when empty
.hostname the hostname without port or IPv6 brackets; null when empty
.isAbsolute whether a scheme is present, including opaque URLs
.path the decoded path; empty when absent or opaque
.port the explicit port number, or null when absent; no default port is inferred
.query decoded query parameters, preserving repeated values; empty when absent; + decodes to a space, and invalid percent escapes raise an error
.rawQuery the undecoded query without ?, null when absent and empty for an explicit ?; malformed query escapes are retained
.resolve resolve a reference against this URL, interpreting . and .. as navigation; the reference may replace the host or scheme
.scheme the lower-case scheme without its colon, or null when absent
.string the URL as text; construction preserves spelling, while edits may re-escape components
.withAddedQueryParam append a value to a decoded query key, preserving its previous values; validates existing query escapes
.withFragment replace the decoded fragment; null removes #, while an empty string adds #
.withHostname replace the hostname, preserving the port and credentials; accepts bare IPv6; null removes the hostname, port and credentials
.withPath replace the decoded path without normalization; a URL with an authority requires an empty path or one starting with /
.withPort return a URL with an explicit nonnegative Int port, or null to clear it; requires a hostname when adding a port and rejects opaque URLs
.withQuery replace query parameters; null removes the query, while an empty map adds a trailing ?
.withQueryParam replace all values of a decoded query key with one value; validates existing query escapes
.withScheme return a URL with a valid scheme, or null to clear it; rejects opaque URLs and nonempty relative paths
.withoutQueryParam remove a decoded query key and all its values; removes ? when no keys remain; validates existing query escapes
.appendPath(segments: [String!]!): URL!

append decoded path segments as data, escaping embedded slashes and literal . or .. segments rather than treating them as navigation

URL("https://example.com").appendPath(Path("users/alice smith").parts)
.escapedPath: String!

the escaped path, preserving valid original escapes

URL("/a%2Fb").escapedPath
.fragment: String

the decoded fragment without #, null when absent and empty for an explicit #

URL("/#a%20b").fragment
.host: String

the host with explicit port and IPv6 brackets, excluding user information; null when empty

URL("https://foo:1234").host
.hostname: String

the hostname without port or IPv6 brackets; null when empty

URL("https://foo:1234").hostname
.isAbsolute: Boolean!

whether a scheme is present, including opaque URLs

URL("mailto:a@example.com").isAbsolute
.path: String!

the decoded path; empty when absent or opaque

URL("/a%20b").path
.port: Int

the explicit port number, or null when absent; no default port is inferred

URL("https://foo:1234").port
.query: Map[[String!]!]!

decoded query parameters, preserving repeated values; empty when absent; + decodes to a space, and invalid percent escapes raise an error

URL("/?q=one&q=two").query
.rawQuery: String

the undecoded query without ?, null when absent and empty for an explicit ?; malformed query escapes are retained

URL("/?q=%zz").rawQuery
.resolve(reference: URL!): URL!

resolve a reference against this URL, interpreting . and .. as navigation; the reference may replace the host or scheme

URL("https://foo/a/b").resolve(URL("../c"))
.scheme: String

the lower-case scheme without its colon, or null when absent

URL("https://foo").scheme
.string: String!

the URL as text; construction preserves spelling, while edits may re-escape components

URL("https://foo/a%20b").string
.withAddedQueryParam(name: String!, value: String!): URL!

append a value to a decoded query key, preserving its previous values; validates existing query escapes

URL("/?q=one").withAddedQueryParam("q", "two")
.withFragment(fragment: String): URL!

replace the decoded fragment; null removes #, while an empty string adds #

URL("/a").withFragment("section one")
.withHostname(hostname: String): URL!

replace the hostname, preserving the port and credentials; accepts bare IPv6; null removes the hostname, port and credentials

URL("https://foo:80/a").withHostname("example.com")
.withPath(path: String!): URL!

replace the decoded path without normalization; a URL with an authority requires an empty path or one starting with /

URL("https://example.com").withPath(Path("/users/alice smith"))
.withPort(port: Int): URL!

return a URL with an explicit nonnegative Int port, or null to clear it; requires a hostname when adding a port and rejects opaque URLs

URL("https://foo").withPort(8443)
.withQuery(query: Map[[String!]!]): URL!

replace query parameters; null removes the query, while an empty map adds a trailing ?

URL("/search").withQuery(["q": ["hello world"]])
.withQueryParam(name: String!, value: String!): URL!

replace all values of a decoded query key with one value; validates existing query escapes

URL("/?q=old").withQueryParam("q", "new")
.withScheme(scheme: String): URL!

return a URL with a valid scheme, or null to clear it; rejects opaque URLs and nonempty relative paths

URL("https://foo/a").withScheme("http")
.withoutQueryParam(name: String!): URL!

remove a decoded query key and all its values; removes ? when no keys remain; validates existing query escapes

URL("/?q=one").withoutQueryParam("q")

[T]! methods#

See Collections. List methods are registered on the List module, so signatures show the element type as the type variable a (and block result types as b). Block params are named item/index — and acc for .reduce.

.all returns true if all elements satisfy the predicate
.any returns true if at least one element satisfies the predicate
.contains checks if the list contains the specified element
.dropFirst returns a new list with the first count elements removed (default 1)
.dropLast returns a new list with the last count elements removed (default 1)
.dropWhile returns a new list with leading elements removed for which the predicate returns true, stopping at the first false
.each iterates over each element in the list, calling the block for each element
.filter returns a new list containing only elements for which the predicate returns true
.find returns the first element for which the predicate returns true, or null if none match
.flatMap returns a new list concatenating the lists the block returns for each element
.groupBy groups original elements by the string key returned by the block; preserves first-seen key order and input order within each group, returning an empty map for an empty list
.indexOf returns the index of the first element equal to the given one, or null if the list doesn't contain it
.isEmpty returns true if the list contains no elements
.join joins the list elements into a string, converting each element as toString does and separating them with the given delimiter
.length returns the number of elements in the list
.map returns a new list with each element transformed by the given function
.reduce reduces the list to a single value using an accumulator function
.reject returns a new list excluding elements for which the predicate returns true
.reverse returns a new list with the elements in reverse order
.sort returns a new list in ascending order (descending: true reverses it), keeping equal elements in their original order. Numbers sort numerically, strings and scalars by their bytes (numeric scalars numerically), false before true, enum values in declaration order, and lists and records element by element
.sortBy returns a new list ordered by the key the block computes for each element, ascending (descending: true reverses it), keeping elements with equal keys in their original order. Keys order like sort's elements; use a list or record for a compound key
.sum adds up a list of numbers (Int! or Float!); an empty list sums to the zero of its element type, 0 or 0.0
.takeFirst returns a new list containing only the first count elements (default 1)
.takeLast returns a new list containing only the last count elements (default 1)
.takeWhile returns a new list containing leading elements for which the predicate returns true, stopping at the first false
.uniq returns a new list with duplicate elements removed, preserving first occurrence order
.all(&block(item: a): Boolean!): Boolean!

returns true if all elements satisfy the predicate

[1, 2, 3].all { x => x > 0 }
.any(&block(item: a): Boolean!): Boolean!

returns true if at least one element satisfies the predicate

[1, 2, 3].any { x => x > 2 }
.contains(element: a): Boolean!

checks if the list contains the specified element

[1, 2, 3].contains(2)
.dropFirst(count: Int = 1): [a]!

returns a new list with the first count elements removed (default 1)

[1, 2, 3, 4].dropFirst(2)
.dropLast(count: Int = 1): [a]!

returns a new list with the last count elements removed (default 1)

[1, 2, 3, 4].dropLast(2)
.dropWhile(&block(item: a): Boolean!): [a]!

returns a new list with leading elements removed for which the predicate returns true, stopping at the first false

[1, 2, 3, 1].dropWhile { x => x < 3 }
.each(&block(item: a, index: Int!): b): [a]!

iterates over each element in the list, calling the block for each element

[1, 2, 3].each { x => print(x) }
.filter(&block(item: a): Boolean!): [a]!

returns a new list containing only elements for which the predicate returns true

[1, 2, 3, 4].filter { x => x > 2 }
.find(&block(item: a): Boolean!): a

returns the first element for which the predicate returns true, or null if none match

[1, 2, 3].find { x => x > 1 }
.flatMap(&block(item: a, index: Int!): [b]!): [b]!

returns a new list concatenating the lists the block returns for each element

[1, 2, 3].flatMap { x => [x, x * 10] }
.groupBy(&block(item: a, index: Int!): String!): Map[[a]!]!

groups original elements by the string key returned by the block; preserves first-seen key order and input order within each group, returning an empty map for an empty list

["apple", "pear", "apricot"].groupBy { item => item.truncate(1) }
.indexOf(element: a): Int

returns the index of the first element equal to the given one, or null if the list doesn't contain it

["a", "b", "c"].indexOf("b")
.isEmpty: Boolean!

returns true if the list contains no elements

[1, 2, 3].isEmpty
.join(separator: String!): String!

joins the list elements into a string, converting each element as toString does and separating them with the given delimiter

["a", "b", "c"].join("-")
.length: Int!

returns the number of elements in the list

[1, 2, 3].length
.map(&block(item: a, index: Int!): b): [b]!

returns a new list with each element transformed by the given function

[1, 2, 3].map { x => x * 2 }
.reduce(initial: b, &block(acc: b, item: a): b): b

reduces the list to a single value using an accumulator function

[1, 2, 3, 4].reduce(0) { acc, x => acc + x }
.reject(&block(item: a): Boolean!): [a]!

returns a new list excluding elements for which the predicate returns true

[1, 2, 3, 4].reject { x => x > 2 }
.reverse: [a]!

returns a new list with the elements in reverse order

[1, 2, 3].reverse
.sort[a: Ordered](descending: Boolean = false): [a]!

returns a new list in ascending order (descending: true reverses it), keeping equal elements in their original order. Numbers sort numerically, strings and scalars by their bytes (numeric scalars numerically), false before true, enum values in declaration order, and lists and records element by element

["b", "c", "a"].sort
.sortBy[a, k: Ordered](descending: Boolean = false, &block(item: a): k!): [a]!

returns a new list ordered by the key the block computes for each element, ascending (descending: true reverses it), keeping elements with equal keys in their original order. Keys order like sort's elements; use a list or record for a compound key

["ccc", "a", "bb"].sortBy { s => s.length }
.sum[a: Numeric]: a

adds up a list of numbers (Int! or Float!); an empty list sums to the zero of its element type, 0 or 0.0

[1, 2, 3, 4].sum
.takeFirst(count: Int = 1): [a]!

returns a new list containing only the first count elements (default 1)

[1, 2, 3, 4].takeFirst(2)
.takeLast(count: Int = 1): [a]!

returns a new list containing only the last count elements (default 1)

[1, 2, 3, 4].takeLast(2)
.takeWhile(&block(item: a): Boolean!): [a]!

returns a new list containing leading elements for which the predicate returns true, stopping at the first false

[1, 2, 3, 1].takeWhile { x => x < 3 }
.uniq: [a]!

returns a new list with duplicate elements removed, preserving first occurrence order

[1, 1, 2, 3, 3].uniq

Map[a]! methods#

See Collections. Map methods are registered on the Map module. Keys are always String!; the value type shows as the type variable a (and block result types as b). Block params are named key/value.

.each iterates over each entry in insertion order, calling the block with the key and value
.get returns the value for the given key, or null if the key is absent
.has returns true if the map contains the given key
.isEmpty returns true if the map contains no entries
.keys returns the map's keys in insertion order
.length returns the number of entries in the map
.map returns a new map with each value transformed by the block; keys are preserved
.merge returns a new map combining this map with another; values from the other map win on key conflicts
.reduce reduces the map to a single value using an accumulator function, iterating in insertion order
.values returns the map's values in insertion order
.with returns a new map with the given key set to the given value
.without returns a new map with the given key removed
.each(&block(key: String!, value: a): b): Map[a]!

iterates over each entry in insertion order, calling the block with the key and value

["a": 1, "b": 2].each { key, value => print(`${key}=${value}`) }
.get(key: String!): a

returns the value for the given key, or null if the key is absent

["a": 1, "b": 2].get("a")
.has(key: String!): Boolean!

returns true if the map contains the given key

["a": 1, "b": 2].has("a")
.isEmpty: Boolean!

returns true if the map contains no entries

[:].isEmpty
.keys: [String!]!

returns the map's keys in insertion order

["a": 1, "b": 2].keys
.length: Int!

returns the number of entries in the map

["a": 1, "b": 2].length
.map(&block(key: String!, value: a): b): Map[b]!

returns a new map with each value transformed by the block; keys are preserved

["a": 1, "b": 2].map { key, value => value * 2 }
.merge(other: Map[a]!): Map[a]!

returns a new map combining this map with another; values from the other map win on key conflicts

["a": 1, "b": 2].merge(["b": 20, "c": 3])
.reduce(initial: b, &block(acc: b, key: String!, value: a): b): b

reduces the map to a single value using an accumulator function, iterating in insertion order

["a": 1, "b": 2].reduce(0) { sum, key, value => sum + value }
.values: [a]!

returns the map's values in insertion order

["a": 1, "b": 2].values
.with(key: String!, value: a): Map[a]!

returns a new map with the given key set to the given value

["a": 1].with("b", 2)
.without(key: String!): Map[a]!

returns a new map with the given key removed

["a": 1, "b": 2].without("a")

JSON, YAML and TOML#

See JSON, YAML, and TOML. JSON/YAML/TOML are Dang's scalars of text in their format, validated on construction ("[1]" :: JSON!); as values they hold their statics: encode serializes any value to a string, decode materializes a string against the expected type (:: T). A same-named schema scalar such as Dagger's JSON is a separate type (Dagger.JSON), while unqualified JSON stays the builtin. Data of any shape decodes into Decoded (see Keeping data undecoded).

JSON#

JSON.decode(data: String!, strict: Boolean = false): Decoded

parses JSON text into an opaque value that is materialized by an expected type; with strict, an object key no field reads, or one repeated, is an error

JSON.decode("[1, 2, 3]") :: [Int!]!
JSON.encode(value: a, indent: String! = "", escapeHTML: Boolean! = true, sortKeys: Boolean! = false): String!

serializes a value to a JSON string. Fields come out in declaration order (a type's as declared, a record's as written) and map entries in insertion order; sortKeys: true sorts every object's keys instead. indent pretty-prints with one copy of it per nesting level (e.g. " "); escapeHTML: false leaves <, >, and & unescaped in strings.

JSON.encode({{tag: "<b>", ids: [1, 2]}}, indent: "  ", escapeHTML: false)

YAML#

A YAML! value may hold several documents; YAML.decode reads a single one.

YAML.decode(data: String!, strict: Boolean = false): Decoded

parses a YAML string into an opaque value that is materialized by an expected type; with strict, a mapping key no field reads, or one repeated, is an error

YAML.decode("[1, 2, 3]") :: [Int!]!
YAML.encode(value: a, sortKeys: Boolean! = false): String!

serializes a value to a YAML string. Fields come out in declaration order (a type's as declared, a record's as written) and map entries in insertion order; sortKeys: true sorts every mapping's keys instead.

YAML.encode({{name: "ci", tags: ["a", "b"]}})

TOML#

TOML.encode requires a table (record) at the top level.

TOML.decode(data: String!, strict: Boolean = false): Decoded

parses a TOML string into an opaque value that is materialized by an expected type; with strict, a key no field reads is an error (TOML never allows repeated keys)

type Settings { count: Int! }
TOML.decode("count = 3") :: Settings
TOML.encode(value: a, indent: String! = ""): String!

serializes a value to a TOML string without indentation by default. indent adds one copy of it per nesting level (e.g. " ") and must contain only spaces and tabs.

TOML.encode({{server: {{port: 8080}}}}, indent: "  ")

Random module#

Random.float: Float!

generates a random float between 0.0 (inclusive) and 1.0 (exclusive)

Random.float
Random.int(min: Int!, max: Int!): Int!

generates a random integer between min (inclusive) and max (exclusive)

Random.int(1, 7)
Random.string: String!

generates a cryptographically random base32 string with at least 128 bits of entropy

Random.string

UUID module#

UUID.v4: String!

generates a random UUID v4 string

UUID.v4
UUID.v7: String!

generates a time-ordered UUID v7 string

UUID.v7

Error types#

See Errors: raise and rescue. These are prelude types rather than builtins, so they aren't part of the generated lists above.

Meta: when generics land properly, update [T]! method signatures to show the actual type parameter rather than handwaving T/U.