### Tuple Syntax Examples Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/types.md Illustrates the syntax for creating tuples of different sizes in Gleam. ```gleam #(a, b) // 2-element tuple (pair) #(a, b, c) // 3-element tuple #(key, value) // Common pattern in dict/list operations ``` -------------------------------- ### Example Code Convention Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/MANIFEST.md Defines the standard format for code examples within the documentation, including imports, usage, and expected output or behavior. ```gleam import gleam/module assertion or realistic usage // Expected output or behavior ``` -------------------------------- ### starts_with Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/bit_array.md Checks whether a BitArray starts with a given prefix. Returns true if it does, false otherwise. ```APIDOC ## starts_with ### Description Checks whether a BitArray starts with a given prefix. Returns true if it does, false otherwise. ### Signature ```gleam pub fn starts_with(bits: BitArray, prefix: BitArray) -> Bool ``` ### Parameters #### Path Parameters - **bits** (BitArray) - Required - BitArray to check - **prefix** (BitArray) - Required - Prefix to find ### Return Bool - True if starts with prefix ### Example ```gleam import gleam/bit_array let data = bit_array.from_string("hello world") let prefix = bit_array.from_string("hello") assert bit_array.starts_with(data, prefix) == True ``` ``` -------------------------------- ### new Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/dict.md Creates a new empty dictionary. This is the starting point for most dictionary operations. ```APIDOC ## new ### Description Creates a new empty dictionary. ### Return Dict(k, v) — Empty dictionary ### Example ```gleam import gleam/dict let d = dict.new() assert dict.is_empty(d) == True ``` ``` -------------------------------- ### Check if String Starts With Prefix Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/string.md Verifies if a string begins with a specified prefix. Returns true if the string starts with the prefix, and false otherwise. ```gleam import gleam/string assert string.starts_with("hello world", "hello") == True assert string.starts_with("hello", "world") == False ``` -------------------------------- ### Function Type Syntax Examples Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/types.md Demonstrates the syntax for defining function types with varying numbers of arguments and return types. ```gleam fn(a) -> b // Function taking a, returning b fn(a, b) -> c // Function taking a and b, returning c fn(a) -> Result(b, e) // Function that may fail fn() -> a // Function with no arguments ``` -------------------------------- ### Create a new empty BytesTree builder Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/bytes_tree.md Use `bytes_tree.new()` to initialize an empty BytesTree. This is the starting point for building a BytesTree. ```gleam import gleam/bytes_tree let tree = bytes_tree.new() ``` -------------------------------- ### first Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/list.md Gets the first element from a list. ```APIDOC ## first ### Description Gets the first element from a list. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **list** (List(a)) - Required - List to get from ### Return - **Result(a, Nil)** - Ok with first element or Error if empty ### Example ```gleam import gleam/list assert list.first([1, 2, 3]) == Ok(1) assert list.first([]) == Error(Nil) ``` ``` -------------------------------- ### Integer Comparison Example Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/types.md Compares two integers using int.compare and demonstrates how to handle the resulting Order type. ```gleam import gleam/int import gleam/order case int.compare(1, 2) { order.Lt -> "1 is less than 2" order.Eq -> "1 equals 2" order.Gt -> "1 is greater than 2" } ``` -------------------------------- ### Create a new empty StringTree builder Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/string_tree.md Use `string_tree.new()` to initialize an empty StringTree. This is the starting point for building strings with this module. ```gleam import gleam/string_tree let tree = string_tree.new() ``` -------------------------------- ### Guard Function Example Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/bool.md Use `guard` for early-return patterns with `use` expressions when a condition is met. The consequence is evaluated immediately. ```gleam import gleam/bool let name = "" use <- bool.guard(when: name == "", return: "Welcome!") "Hello, " <> name // Returns: "Welcome!" ``` -------------------------------- ### string_tree.new Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/string_tree.md Creates a new, empty StringTree builder. This is the starting point for constructing strings using the StringTree module. ```APIDOC ## string_tree.new ### Description Creates a new empty StringTree builder. ### Return StringTree — Empty tree ### Example ```gleam import gleam/string_tree let tree = string_tree.new() ``` ``` -------------------------------- ### Create a new empty dictionary Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/dict.md Use `dict.new()` to create an empty dictionary. This is useful for starting new data structures. ```gleam import gleam/dict let d = dict.new() assert dict.is_empty(d) == True ``` -------------------------------- ### Install gleam_stdlib Source: https://github.com/gleam-lang/stdlib/blob/main/README.md Add the gleam_stdlib package to your Gleam project using the gleam add command. This ensures you have the latest version compatible with Gleam 1.x. ```sh gleam add gleam_stdlib@1 ``` -------------------------------- ### Parse and Process URI Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/START_HERE.md Example of parsing a URI string and handling the result. It demonstrates pattern matching on the `Ok` and `Error` cases returned by `uri.parse`. Requires importing the `gleam/uri` module. ```gleam import gleam/uri case uri.parse("https://example.com/path?key=value") { Ok(u) -> process(u.path) Error(_) -> handle_invalid() } ``` -------------------------------- ### Use Int Type for Base16 Conversion Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/types.md Shows an example of using the Int type for numerical operations, specifically converting to base16. ```gleam import gleam/int let x = 42 assert int.to_base16(x) == "2a" ``` -------------------------------- ### Parse URI String Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/README.md Parses a URI string into its components. The example shows how to access parts like scheme, host, port, path, and query parameters after successful parsing. ```gleam import gleam/uri case uri.parse("https://example.com:8080/api/users?id=123") { Ok(u) -> { // Access u.scheme, u.host, u.port, u.path, u.query } Error(_) -> Nil } ``` -------------------------------- ### int.parse Function Example Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/MANIFEST.md Demonstrates parsing a string into an integer using the `gleam/int` module. Shows successful parsing and error handling for invalid input. ```gleam import gleam/int assert int.parse("42") == Ok(42) assert int.parse("abc") == Error(Nil) ``` -------------------------------- ### Get all keys from a dictionary Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/dict.md Use `dict.keys()` to retrieve a list of all keys present in the dictionary. The order of keys in the returned list is not guaranteed. ```gleam import gleam/dict let d = dict.new() |> dict.insert("a", 1) |> dict.insert("b", 2) let ks = dict.keys(d) // ks contains "a" and "b" in some order ``` -------------------------------- ### get Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/dict.md Retrieves a value from a dictionary by key. Returns `Ok(value)` if the key is found, or `Error(Nil)` if the key does not exist. ```APIDOC ## get ### Description Retrieves a value from a dictionary by key. ### Parameters #### Path Parameters - **from** (Dict(k, v)) - Required - Dictionary to search - **get** (k) - Required - Key to look up ### Return Result(v, Nil) — Value or Error if key not found ### Example ```gleam import gleam/dict let d = dict.new() |> dict.insert("name", "Alice") assert dict.get(d, "name") == Ok("Alice") assert dict.get(d, "age") == Error(Nil) ``` ``` -------------------------------- ### Lazy Guard Function Example Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/bool.md Use `lazy_guard` when both the consequence and alternative computations should be deferred until needed. This is useful for performance when computations are expensive. ```gleam import gleam/bool let name = "" let greeting = fn() { "Hello, " <> name } use <- bool.lazy_guard(when: name == "", otherwise: greeting) "Welcome!" // Returns: "Welcome!" when name is empty ``` -------------------------------- ### Check if BitArray Starts with Prefix Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/bit_array.md Determines if a given BitArray begins with a specified prefix BitArray. This is useful for pattern matching or validating data streams. ```gleam import gleam/bit_array let data = bit_array.from_string("hello world") let prefix = bit_array.from_string("hello") assert bit_array.starts_with(data, prefix) == True ``` -------------------------------- ### Drop Graphemes from Start of String Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/string.md Removes a specified number of graphemes from the beginning of a string. Use this when you need to truncate a string from its start. ```gleam import gleam/string assert string.drop_start("hello", 2) == "llo" assert string.drop_start("hello", 0) == "hello" ``` -------------------------------- ### Use Nil Type for Side Effects Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/types.md Shows an example where the Nil type is returned, typically indicating a side effect operation like printing. ```gleam import gleam/io io.println("Hello") // Returns Nil (side effect only) ``` -------------------------------- ### Get First Element of List Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/list.md Gets the first element from a list. Returns Ok with the element if the list is not empty, otherwise returns Error(Nil). ```gleam import gleam/list assert list.first([1, 2, 3]) == Ok(1) assert list.first([]) == Error(Nil) ``` -------------------------------- ### Use Dict Type for Key-Value Storage Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/types.md Shows how to create a dictionary and insert key-value pairs, then retrieve a value by its key. ```gleam import gleam/dict let d = dict.new() |> dict.insert("a", 1) |> dict.insert("b", 2) assert dict.get(d, "a") == Ok(1) assert dict.keys(d) |> list.contains(_, "b") ``` -------------------------------- ### Get Rest of List Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/list.md Gets all elements except the first from a list. Returns Ok with the remaining elements if the list is not empty, otherwise returns Error(Nil). ```gleam import gleam/list assert list.rest([1, 2, 3]) == Ok([2, 3]) assert list.rest([1]) == Ok([]) assert list.rest([]) == Error(Nil) ``` -------------------------------- ### new Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/list.md Creates and returns a new, empty list. ```APIDOC ## new ### Description Creates a new empty list. ### Signature ```gleam pub fn new() -> List(a) ``` ### Return List(a) — Empty list ### Example ```gleam import gleam/list assert list.new() == [] ``` ``` -------------------------------- ### API Reference Document Structure Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/MANIFEST.md Illustrates the typical structure of an API reference document for a Gleam module, including type definitions, functions, signatures, parameter tables, examples, and source references. ```markdown Module Name (title) └─ Type definitions (if applicable) └─ Functions (alphabetical) ├─ Function signature (code block) ├─ Parameter table (markdown table) ├─ Return type description ├─ Code example (executable) └─ Source reference ``` -------------------------------- ### starts_with Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/string.md Determines if a string begins with a specified prefix. Returns true if it does, and false otherwise. ```APIDOC ## starts_with ### Description Checks whether a string starts with a prefix. ### Signature ```gleam pub fn starts_with(string: String, prefix: String) -> Bool ``` ### Parameters - **string** (String) - String to check - **prefix** (String) - Prefix to find ### Return Bool - True if starts with prefix, False otherwise ### Example ```gleam import gleam/string assert string.starts_with("hello world", "hello") == True assert string.starts_with("hello", "world") == False ``` ``` -------------------------------- ### rest Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/list.md Gets all elements except the first from a list. ```APIDOC ## rest ### Description Gets all elements except the first from a list. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **list** (List(a)) - Required - List to process ### Return - **Result(List(a), Nil)** - Ok with remaining elements or Error if empty ### Example ```gleam import gleam/list assert list.rest([1, 2, 3]) == Ok([2, 3]) assert list.rest([1]) == Ok([]) assert list.rest([]) == Error(Nil) ``` ``` -------------------------------- ### Build and Convert StringTree Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/types.md Builds a StringTree by appending strings and converts it to a final String. Requires importing gleam/string_tree. ```gleam import gleam/string_tree let tree = string_tree.new() |> string_tree.append_string("Hello") |> string_tree.append_string(" ") |> string_tree.append_string("World") let result = string_tree.to_string(tree) ``` -------------------------------- ### slice Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/string.md Extracts a portion of a string based on a starting grapheme position and a specified length. ```APIDOC ## slice ### Description Extracts a substring by grapheme position and length. ### Signature ```gleam pub fn slice(x: String, from start: Int, length length: Int) -> String ``` ### Parameters - **x** (String) - String to slice - **start** (Int) - Starting position - **length** (Int) - Number of graphemes ### Return String - Substring ### Example ```gleam import gleam/string assert string.slice("hello", 1, 3) == "ell" assert string.slice("hello", 0, 2) == "he" ``` ``` -------------------------------- ### Define a greet function in Gleam Source: https://github.com/gleam-lang/stdlib/blob/main/README.md This snippet defines a simple 'greet' function that takes a String and prints a greeting to the console using the io.println function. It requires importing the gleam/io module. ```gleam import gleam/io pub fn greet(name: String) -> Nil { io.println("Hello " <> name <> "!") } ``` -------------------------------- ### Get List Length Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/list.md Returns the number of elements in a list. This operation runs in linear time. ```gleam import gleam/list assert list.length([]) == 0 assert list.length([1, 2, 3]) == 3 ``` -------------------------------- ### Build Strings Efficiently Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/START_HERE.md Demonstrates the use of `string_tree` for efficient string construction by appending multiple string segments. Requires importing the `gleam/string_tree` module. ```gleam import gleam/string_tree string_tree.new() |> string_tree.append("Hello ") |> string_tree.append("World") |> string_tree.to_string() ``` -------------------------------- ### new Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/bytes_tree.md Creates a new empty BytesTree builder. ```APIDOC ## new ### Description Creates a new empty BytesTree builder. ### Return BytesTree — Empty tree ### Example ```gleam import gleam/bytes_tree let tree = bytes_tree.new() ``` ``` -------------------------------- ### Get URI Origin Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/uri.md Extracts the origin (scheme, host, and port) from a URI. Requires the URI to have a host. ```gleam import gleam/uri let uri = uri.Uri( scheme: Some("https"), host: Some("example.com"), port: Some(443), path: "/path", ..uri.empty ) assert uri.origin(uri) == Ok("https://example.com:443") ``` -------------------------------- ### Get Absolute Value of Integer Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/int.md Returns the absolute value of an integer. This function ensures the result is non-negative. ```gleam import gleam/int assert int.absolute_value(-42) == 42 assert int.absolute_value(42) == 42 assert int.absolute_value(0) == 0 ``` -------------------------------- ### Build and Convert BytesTree Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/types.md Constructs a BytesTree by appending strings and then converts it to a BitArray. Requires importing gleam/bytes_tree and gleam/bit_array. ```gleam import gleam/bytes_tree import gleam/bit_array let tree = bytes_tree.new() |> bytes_tree.append_string("Hello") |> bytes_tree.append_string(" World") let bytes = bytes_tree.to_bit_array(tree) ``` -------------------------------- ### take Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/list.md Takes a specified number of elements from the beginning of a list. It returns a new list containing the first 'n' elements. ```APIDOC ## take ### Description Takes the first n elements from a list. ### Signature ```gleam pub fn take(from list: List(a), up_to n: Int) -> List(a) ``` ### Parameters #### Arguments - **list** (List(a)) - List to take from - **n** (Int) - Number of elements to take ### Return List(a) — List with first n elements ### Example ```gleam import gleam/list assert list.take([1, 2, 3, 4], 2) == [1, 2] assert list.take([1, 2], 5) == [1, 2] ``` ``` -------------------------------- ### Get the size of a set Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/set.md Use `set.size()` to retrieve the number of elements in a set. An empty set has a size of 0. ```gleam import gleam/set assert set.new() |> set.size == 0 assert set.new() |> set.insert(1) |> set.size == 1 ``` -------------------------------- ### Using try_recover with Different Results Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/result.md Demonstrates how try_recover handles Ok values and Error values with different recovery functions. The recovery function can either succeed or fail. ```gleam import gleam/result assert result.try_recover(Ok(1), fn(_) { Ok(2) }) == Ok(1) assert result.try_recover(Error(1), fn(x) { Ok(x + 1) }) == Ok(2) assert result.try_recover(Error(1), fn(_) { Error("recovery failed") }) == Error("recovery failed") ``` -------------------------------- ### Get Absolute Value of a Float Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/float.md Returns the absolute value of a float. Use this for ensuring a non-negative float value. ```gleam import gleam/float assert float.absolute_value(-3.5) == 3.5 assert float.absolute_value(3.5) == 3.5 ``` -------------------------------- ### Extract Substring by Slice Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/string.md Extracts a portion of a string based on a starting grapheme position and a specified length. Indices are zero-based. ```gleam import gleam/string assert string.slice("hello", 1, 3) == "ell" assert string.slice("hello", 0, 2) == "he" ``` -------------------------------- ### Create an empty set Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/set.md Use `set.new()` to create a new, empty set. Verify emptiness with `set.is_empty()`. ```gleam import gleam/set let s = set.new() assert set.is_empty(s) == True ``` -------------------------------- ### Efficiently build binary data with BytesTree Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/bytes_tree.md Demonstrates the efficient construction of binary data using BytesTree by chaining append operations. This method is preferred over repeated bit_array.append() for performance. ```gleam import gleam/bytes_tree // Efficient way to build binary data let result = bytes_tree.new() |> bytes_tree.append_string("Name: ") |> bytes_tree.append_string(user_name) |> bytes_tree.append_string("\nAge: ") |> bytes_tree.append_string(int.to_string(age)) |> bytes_tree.to_bit_array() ``` -------------------------------- ### Print String to Standard Output (With Newline) Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/io.md Use `io.println` to output a string to standard output, followed by a newline character. This ensures each output appears on its own line. ```gleam import gleam/io io.println("Hello") io.println("World") // Output: // Hello // World ``` -------------------------------- ### Get the length of a string Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/string.md The `length` function returns the number of graphemes in a string. This ensures accurate counting for multi-byte characters. ```gleam import gleam/string assert string.length("") == 0 assert string.length("hello") == 5 assert string.length("👍") == 1 ``` -------------------------------- ### Root Documentation Structure Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/MANIFEST.md Outlines the content structure for the main root documentation files: README.md, INDEX.md, and types.md. ```markdown README.md ├─ Overview of project ├─ Module descriptions ├─ Type system explanations ├─ Common patterns ├─ Performance notes └─ Use cases INDEX.md ├─ Documentation structure ├─ Quick navigation by purpose ├─ Alphabetical module reference ├─ Cross-module patterns └─ Statistics types.md ├─ Built-in types ├─ Library-defined types ├─ Type conventions ├─ Comparison semantics └─ Example patterns ``` -------------------------------- ### Get the size of a dictionary Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/dict.md Use `dict.size()` to determine the number of key-value pairs in a dictionary. This operation runs in constant time. ```gleam import gleam/dict assert dict.new() |> dict.size == 0 assert dict.new() |> dict.insert("a", 1) |> dict.size == 1 ``` -------------------------------- ### Create a New Empty List Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/list.md The `new` function creates and returns an empty list. This is useful for initializing lists before adding elements. ```gleam import gleam/list assert list.new() == [] ``` -------------------------------- ### Create Dynamic Values Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/types.md Demonstrates creating dynamic values for integers and strings using the gleam/dynamic module. ```gleam import gleam/dynamic let x = dynamic.int(42) let y = dynamic.string("hello") ``` -------------------------------- ### Get all values from a dictionary Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/dict.md Use `dict.values()` to retrieve a list of all values stored in the dictionary. The order of values corresponds to the order of keys. ```gleam import gleam/dict let d = dict.new() |> dict.insert("a", 1) |> dict.insert("b", 2) let vs = dict.values(d) // vs contains 1 and 2 in some order ``` -------------------------------- ### Combine List of Options Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/option.md Use all to combine a list of options. If all elements are Some, it returns Some containing a list of the values. If any element is None, it returns None. ```gleam import gleam/option assert option.all([Some(1), Some(2)]) == Some([1, 2]) assert option.all([Some(1), None]) == None ``` -------------------------------- ### Get Byte Size of StringTree Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/string_tree.md Returns the number of bytes (UTF-8) in the final string representation of a StringTree. Useful for estimating memory usage. ```gleam import gleam/string_tree let tree = string_tree.new() |> string_tree.append("hello") assert string_tree.byte_size(tree) == 5 ``` -------------------------------- ### wrap Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/list.md Creates a new list containing a single provided element. ```APIDOC ## wrap ### Description Creates a list with a single element. ### Signature ```gleam pub fn wrap(item: a) -> List(a) ``` ### Parameters #### Arguments - **item** (a) - Element to wrap ### Return List(a) — List containing single element ### Example ```gleam import gleam/list assert list.wrap(1) == [1] ``` ``` -------------------------------- ### Partition Results into Ok and Error Lists Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/result.md Use `partition` to separate a list of Results into two distinct lists: one containing all Ok values and another containing all Error values. Note that the values are in reverse order of their appearance in the input list. ```gleam import gleam/result assert result.partition([Ok(1), Error("a"), Ok(2)]) == #([2, 1], ["a"]) ``` -------------------------------- ### Efficiently Build Large Strings with StringTree Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/string_tree.md Demonstrates the efficient construction of large strings by appending segments to a StringTree. This method is significantly more performant than repeated string concatenations. ```gleam import gleam/string_tree // Efficient for building large strings let result = string_tree.new() |> string_tree.append("User Report\n") |> string_tree.append("Name: ") |> string_tree.append(user_name) |> string_tree.append("\nEmail: ") |> string_tree.append(email) |> string_tree.append("\n") |> string_tree.to_string() ``` -------------------------------- ### Tuple Usage with Pair Module Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/types.md Shows how to create a 2-element tuple and access its elements using functions from the gleam/pair module. ```gleam import gleam/pair let p = #(1, "hello") assert pair.first(p) == 1 assert pair.second(p) == "hello" ``` -------------------------------- ### Get the byte size of a BytesTree Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/bytes_tree.md Calculates the total number of bytes that the final BitArray will contain. This is useful for pre-allocating buffers or estimating memory usage. ```gleam import gleam/bytes_tree let tree = bytes_tree.new() |> bytes_tree.append_string("hello") assert bytes_tree.byte_size(tree) == 5 ``` -------------------------------- ### Prepend a string to a StringTree Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/string_tree.md Use `string_tree.prepend()` to add a string to the beginning of an existing StringTree. This is useful for constructing strings in reverse or adding prefixes. ```gleam import gleam/string_tree let tree = string_tree.new() |> string_tree.append("World") |> string_tree.prepend("Hello ") ``` -------------------------------- ### Extract Error or Default Value Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/result.md Use `unwrap_error` to get the error value from a Result. If the Result is Ok, a provided default value is returned instead. ```gleam import gleam/result assert result.unwrap_error(Error(1), 0) == 1 assert result.unwrap_error(Ok("ok"), 0) == 0 ``` -------------------------------- ### Extract First Element of a Pair Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/pair.md Use `pair.first` to get the first element from a 2-element tuple. This function is useful when you only need the initial value of a pair. ```gleam import gleam/pair assert pair.first(#("hello", 42)) == "hello" assert pair.first(#(1, 2)) == 1 ``` -------------------------------- ### Create a StringTree from a list of strings Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/string_tree.md Use `string_tree.from_strings()` to efficiently create a StringTree by combining multiple strings from a list. This is a convenient way to initialize a tree with several string parts. ```gleam import gleam/string_tree let tree = string_tree.from_strings(["Hello", " ", "World"]) ``` -------------------------------- ### Provide Second Option if First is None Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/option.md Use `or` to return the first Option if it is `Some`. If the first Option is `None`, the second Option is returned, regardless of whether it is `Some` or `None`. ```gleam import gleam/option assert option.or(Some(1), Some(2)) == Some(1) assert option.or(None, Some(2)) == Some(2) assert option.or(None, None) == None ``` -------------------------------- ### Get a value from a dictionary by key Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/dict.md Use `dict.get()` to retrieve a value associated with a specific key. Returns `Ok(value)` if the key is found, or `Error(Nil)` if not. ```gleam import gleam/dict let d = dict.new() |> dict.insert("name", "Alice") assert dict.get(d, "name") == Ok("Alice") assert dict.get(d, "age") == Error(Nil) ``` -------------------------------- ### println Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/io.md Prints a string to standard output followed by a newline. It accepts a string argument and returns Nil. ```APIDOC ## println ### Description Prints a string to standard output followed by a newline. ### Signature ```gleam pub fn println(string: String) -> Nil ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **string** (String) - Required - Text to print ### Request Example ```gleam import gleam/io io.println("Hello") io.println("World") ``` ### Response #### Success Response (Nil) - Returns Nil upon successful execution. #### Response Example ```gleam Nil ``` ``` -------------------------------- ### Get Bit Size of BitArray Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/bit_array.md Returns the total number of bits contained within a BitArray. Useful for understanding the precise memory footprint or for bit-level operations. ```gleam import gleam/bit_array let bytes = bit_array.from_string("hi") assert bit_array.bit_size(bytes) == 16 ``` -------------------------------- ### Convert Result to Option Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/option.md Use from_result to convert a Result to an Option. Ok(a) becomes Some(a), and an Error becomes None. ```gleam import gleam/option assert option.from_result(Ok(42)) == Some(42) assert option.from_result(Error("error")) == None ``` -------------------------------- ### fold Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/set.md Reduces a set to a single value by iterating over elements. This function applies a given function cumulatively to the elements of the set, from left to right, starting with an initial value. ```APIDOC ## fold ### Description Reduces a set to a single value by iterating over elements. ### Signature ```gleam pub fn fold( over set: Set(member), from initial: a, with fun: fn(a, member) -> a, ) -> a ``` ### Parameters #### Path Parameters - **set** (Set(member)) - Required - Set to fold - **initial** (a) - Required - Starting accumulator - **fun** (fn(a, member) -> a) - Required - Function to apply ### Return a — Final accumulated value ### Example ```gleam import gleam/set let s = set.from_list([1, 2, 3]) let sum = set.fold(s, 0, fn(acc, x) { acc + x }) assert sum == 6 ``` ``` -------------------------------- ### Build String Efficiently Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/INDEX.md Constructs a string by appending multiple parts using `string_tree`. This is efficient for building strings incrementally. ```gleam import gleam/string_tree string_tree.new() |> string_tree.append("User: ") |> string_tree.append(name) |> string_tree.to_string() ``` -------------------------------- ### Handle Optional User Data Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/README.md Retrieves an optional user value, maps it to get the user's email if the user exists, and provides a default email if the user is absent. ```gleam import gleam/option maybe_user |> option.map(get_user_email) |> option.unwrap("user@example.com") ``` -------------------------------- ### compare Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/float.md Compares two floats. Returns Lt, Eq, or Gt. ```APIDOC ## compare ### Description Compares two floats. Returns Lt, Eq, or Gt. ### Signature ```gleam pub fn compare(a: Float, with b: Float) -> Order ``` ### Parameters #### Path Parameters - **a** (Float) - Required - First float - **b** (Float) - Required - Second float ### Return Order - Lt, Eq, or Gt ### Example ```gleam import gleam/float import gleam/order assert float.compare(1.0, 2.0) == order.Lt assert float.compare(2.0, 2.0) == order.Eq ``` ``` -------------------------------- ### fold Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/dict.md Reduces a dictionary to a single value by applying a function to each key-value pair, starting with an initial accumulator value. The function takes the current accumulator, key, and value, and returns the new accumulator. ```APIDOC ## fold ### Description Reduces a dictionary to a single value by iterating over key-value pairs. ### Signature ```gleam pub fn fold( over dict: Dict(k, v), from initial: a, with fun: fn(a, k, v) -> a, ) -> a ``` ### Parameters #### Path Parameters - **dict** (Dict(k, v)) - Required - Dictionary to fold - **initial** (a) - Required - Starting accumulator - **fun** (fn(a, k, v) -> a) - Required - Function to apply ### Return a — Final accumulated value ### Example ```gleam import gleam/dict let d = dict.new() |> dict.insert("a", 1) |> dict.insert("b", 2) let sum = dict.fold(d, 0, fn(acc, _, v) { acc + v }) assert sum == 3 ``` ``` -------------------------------- ### Wrap an Item in a List Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/list.md The `wrap` function takes a single item and returns a new list containing only that item. This is a convenient way to create a singleton list. ```gleam import gleam/list assert list.wrap(1) == [1] ``` -------------------------------- ### prepend Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/bytes_tree.md Prepends a BitArray to the beginning of a BytesTree. ```APIDOC ## prepend ### Description Prepends a BitArray to the beginning of a BytesTree. ### Parameters #### Path Parameters - **to** (BytesTree) - Required - Tree to prepend to - **prefix** (BitArray) - Required - BitArray to prepend ### Return BytesTree — New tree with prepended data ### Example ```gleam import gleam/bytes_tree import gleam/bit_array let tree = bytes_tree.new() |> bytes_tree.append(bit_array.from_string("World")) |> bytes_tree.prepend(bit_array.from_string("Hello ")) ``` ``` -------------------------------- ### Take Elements from a List Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/list.md The `take` function selects a specified number of elements from the beginning of a list. If the number to take exceeds the list length, the entire list is returned. ```gleam import gleam/list assert list.take([1, 2, 3, 4], 2) == [1, 2] assert list.take([1, 2], 5) == [1, 2] ``` -------------------------------- ### string_tree.prepend Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/string_tree.md Prepends a given string to the beginning of an existing StringTree. This operation returns a new StringTree with the prefix added. ```APIDOC ## string_tree.prepend ### Description Prepends a string to the beginning of a StringTree. ### Method `prepend(to: StringTree, prefix: String) -> StringTree` ### Parameters #### Path Parameters - **tree** (StringTree) - Required - Tree to prepend to - **prefix** (String) - Required - String to prepend ### Return StringTree — New tree with prepended string ### Example ```gleam import gleam/string_tree let tree = string_tree.new() |> string_tree.append("World") |> string_tree.prepend("Hello ") ``` ``` -------------------------------- ### then Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/option.md Chains options together. If `Some`, applies a function that returns an Option. If `None`, returns `None`. ```APIDOC ## then ### Description Chains options together. If `Some`, applies a function that returns an Option. If `None`, returns `None`. ### Function Signature `pub fn then(option: Option(a), apply fun: fn(a) -> Option(b)) -> Option(b)` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **option** (Option(a)) - Required - Option to process - **fun** (fn(a) -> Option(b)) - Required - Function returning Option ### Return Option(b) — Result of function or None ### Example ```gleam import gleam/option assert option.then(Some(5), fn(x) { Some(x * 2) }) == Some(10) assert option.then(Some(5), fn(_) { None }) == None assert option.then(None, fn(x) { Some(x * 2) }) == None ``` ``` -------------------------------- ### compare Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/int.md Compares two integers and returns their ordering. It indicates whether the first integer is less than, equal to, or greater than the second. ```APIDOC ## compare ### Description Compares two integers. ### Signature ```gleam pub fn compare(a: Int, with b: Int) -> Order ``` ### Parameters #### Path Parameters - **a** (Int) - Required - First integer - **b** (Int) - Required - Second integer ### Return Order - Lt, Eq, or Gt ### Example ```gleam import gleam/int import gleam/order assert int.compare(1, 2) == order.Lt assert int.compare(2, 2) == order.Eq assert int.compare(3, 2) == order.Gt ``` ``` -------------------------------- ### or Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/option.md Returns the first option if `Some`, otherwise returns the second option. ```APIDOC ## or ### Description Returns the first option if `Some`, otherwise returns the second option. ### Function Signature `pub fn or(first: Option(a), second: Option(a)) -> Option(a)` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **first** (Option(a)) - Required - First option - **second** (Option(a)) - Required - Second option ### Return Option(a) — First if Some, otherwise second ### Example ```gleam import gleam/option assert option.or(Some(1), Some(2)) == Some(1) assert option.or(None, Some(2)) == Some(2) assert option.or(None, None) == None ``` ``` -------------------------------- ### Map and Unwrap Optional Values Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/START_HERE.md Shows how to transform an optional value using `option.map` and then extract its value with a default using `option.unwrap`. Requires importing the `gleam/option` module. ```gleam import gleam/option maybe_value |> option.map(fn(x) { x + 1 }) |> option.unwrap(0) ``` -------------------------------- ### Chain Options with `then` Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/option.md Use `then` to chain operations that return Options. If the initial Option is `Some`, the provided function is applied; otherwise, `None` is returned immediately. ```gleam import gleam/option assert option.then(Some(5), fn(x) { Some(x * 2) }) == Some(10) assert option.then(Some(5), fn(_) { None }) == None assert option.then(None, fn(x) { Some(x * 2) }) == None ``` -------------------------------- ### Prepend one StringTree to another Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/string_tree.md Use `string_tree.prepend_tree()` to efficiently add one StringTree to the beginning of another. This is the inverse of `append_tree`. ```gleam import gleam/string_tree let tree1 = string_tree.new() |> string_tree.append("Hello") let tree2 = string_tree.new() |> string_tree.append(" World") let combined = string_tree.prepend_tree(tree2, tree1) ``` -------------------------------- ### compare Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/string.md Compares two strings lexicographically. ```APIDOC ## compare ### Description Compares two strings lexicographically. ### Function Signature pub fn compare(a: String, b: String) -> order.Order ### Parameters #### Path Parameters - **a** (String) - Required - First string - **b** (String) - Required - Second string ### Return order.Order — Lt, Eq, or Gt ### Example ```gleam import gleam/string import gleam/order assert string.compare("a", "b") == order.Lt assert string.compare("hello", "hello") == order.Eq ``` ``` -------------------------------- ### new Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/set.md Creates a new empty set. The `Set(member)` type represents a set of unique values with no duplicates. ```APIDOC ## new ### Description Creates a new empty set. ### Return Set(member) — Empty set ### Example ```gleam import gleam/set let s = set.new() assert set.is_empty(s) == True ``` ``` -------------------------------- ### new Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/pair.md Creates a new pair from two values. ```APIDOC ## new ### Description Creates a new pair from two values. ### Parameters #### Path Parameters - **first** (a) - Required - First element - **second** (b) - Required - Second element ### Return #(a, b) — New pair ### Example ```gleam import gleam/pair assert pair.new("hello", 42) == #("hello", 42) assert pair.new(1, 2) == #(1, 2) ``` ``` -------------------------------- ### all Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/option.md Combines a list of options into a single option containing a list of values. Returns Some with the list if all input options are Some, otherwise returns None. ```APIDOC ## all ### Description Combines a list of options. If all are `Some`, returns `Some` with a list of values. If any is `None`, returns `None`. ### Signature ```gleam pub fn all(list: List(Option(a))) -> Option(List(a)) ``` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters - **list** (List(Option(a))) - Required - List of options. ### Return Option(List(a)) — Some list or None. ### Example ```gleam import gleam/option assert option.all([Some(1), Some(2)]) == Some([1, 2]) assert option.all([Some(1), None]) == None ``` ``` -------------------------------- ### Immutable List Operations Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/README.md Demonstrates immutability by showing that operations like `list.append` return a new list without modifying the original. ```gleam import gleam/list let original = [1, 2, 3] let modified = list.append(original, [4]) // original: [1, 2, 3] // modified: [1, 2, 3, 4] ``` -------------------------------- ### Gleam Standard Library Directory Structure Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/INDEX.md Overview of the Gleam standard library's documentation structure, showing the organization of markdown files for different modules and the API reference. ```markdown /workspace/home/output/ ├── README.md # Main overview and guide ├── INDEX.md # This file ├── types.md # Complete type definitions reference └── api-reference/ # Individual module documentation ├── bool.md # Boolean logic ├── result.md # Result type and error handling ├── option.md # Optional values ├── list.md # List operations ├── string.md # String manipulation ├── int.md # Integer operations ├── float.md # Float operations ├── dict.md # Dictionary/hash map ├── set.md # Set operations ├── bit_array.md # Binary data handling ├── bytes_tree.md # Binary tree builder ├── string_tree.md # String tree builder ├── uri.md # URI parsing and manipulation ├── pair.md # Tuple operations ├── order.md # Comparison ordering └── io.md # Input/output ``` -------------------------------- ### Prepend one BytesTree to another Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/bytes_tree.md Use `bytes_tree.prepend_tree()` to efficiently add one BytesTree to the beginning of another. This leverages the tree structure for performance. ```gleam import gleam/bytes_tree let tree1 = bytes_tree.new() |> bytes_tree.append_string("Hello") let tree2 = bytes_tree.new() |> bytes_tree.append_string(" World") let combined = bytes_tree.prepend_tree(tree1, tree2) ``` -------------------------------- ### Use String Type for Uppercasing Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/types.md Demonstrates a basic operation on the String type, converting text to uppercase. ```gleam import gleam/string let text = "hello" assert string.uppercase(text) == "HELLO" ``` -------------------------------- ### Combine List of Results with 'all' Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/result.md The `all` function aggregates a list of Results. It returns an Ok containing a list of all success values if every element is Ok. If any element is an Error, it returns the first encountered Error. ```gleam import gleam/result assert result.all([Ok(1), Ok(2)]) == Ok([1, 2]) assert result.all([Ok(1), Error("err")]) == Error("err") ``` -------------------------------- ### and Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/bool.md Returns the logical AND of two booleans. Evaluates both arguments. ```APIDOC ## and ### Description Returns the logical AND of two booleans. Evaluates both arguments. ### Function Signature ```gleam pub fn and(a: Bool, b: Bool) -> Bool ``` ### Parameters #### Parameters - **a** (Bool) - Required - First operand - **b** (Bool) - Required - Second operand ### Return Value Bool - True if both operands are True, False otherwise ### Example ```gleam import gleam/bool assert bool.and(True, True) == True assert bool.and(True, False) == False assert bool.and(False, False) == False ``` ``` -------------------------------- ### Filter and Map List Elements Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/START_HERE.md Demonstrates common list manipulation techniques: filtering elements based on a condition and then mapping a transformation function over the remaining elements. Requires importing the `gleam/list` module. ```gleam import gleam/list [1, 2, 3] |> list.filter(fn(x) { x > 1 }) |> list.map(fn(x) { x * 2 }) ``` -------------------------------- ### pub fn byte_size(tree: BytesTree) -> Int Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/bytes_tree.md Returns the number of bytes that will be in the final BitArray. ```APIDOC ## byte_size ### Description Returns the number of bytes that will be in the final BitArray. ### Signature pub fn byte_size(tree: BytesTree) -> Int ### Parameters - **tree** (BytesTree) - Required - Tree to measure ### Returns - **Int** - Number of bytes ### Example ```gleam import gleam/bytes_tree let tree = bytes_tree.new() |> bytes_tree.append_string("hello") assert bytes_tree.byte_size(tree) == 5 ``` ``` -------------------------------- ### or Source: https://github.com/gleam-lang/stdlib/blob/main/_autodocs/api-reference/result.md Returns the first Result if it is Ok. Otherwise, it returns the second Result. ```APIDOC ## or ### Description Returns the first value if Ok, otherwise returns the second value. ### Signature pub fn or(first: Result(a, e), second: Result(a, e)) -> Result(a, e) ### Parameters #### Path Parameters - **first** (Result(a, e)) - Required - First result - **second** (Result(a, e)) - Required - Second result ### Return Result(a, e) - First if Ok, otherwise second ### Example ```gleam import gleam/result assert result.or(Ok(1), Ok(2)) == Ok(1) assert result.or(Error("a"), Ok(2)) == Ok(2) assert result.or(Error("a"), Error("b")) == Error("b") ``` ```