### Build Project Documentation with VitePress Source: https://github.com/mendrik/aivi/blob/main/specs/README.md Instructions for installing dependencies and running development or build commands for the project's documentation using VitePress. Assumes Node.js and npm are installed. ```bash npm install npm run docs:dev ``` ```bash npm run docs:build ``` -------------------------------- ### Aivi: Config Binding Example Source: https://github.com/mendrik/aivi/blob/main/specs/syntax/bindings.md Provides a practical example of using bindings in Aivi for configuration settings. This demonstrates how to define and access configuration parameters. ```aivi config = { database: { host: "localhost", port: 5432 }, api_key: "secret123" } db_host = config.database.host api_key = config.api_key print(db_host) // Output: localhost print(api_key) // Output: secret123 ``` -------------------------------- ### HTTP GET Request Example Source: https://github.com/mendrik/aivi/blob/main/specs/syntax/external_sources.md Shows how to perform an HTTP GET request to fetch data from a specified URL using `Source.http.get`. This is a fundamental example for integrating with web APIs. ```aivi Source.http.get("https://api.example.com/data") ``` -------------------------------- ### Aivi URL Usage Examples Source: https://github.com/mendrik/aivi/blob/main/specs/stdlib/system/url.md Illustrates practical use cases and examples of the aivi.url domain's functionalities. ```aivi // Example: Modifying a URL let url = url.parse("http://old.com") let newUrl = { ...url, protocol: "https", host: "new.com" } print(url.toString(newUrl)) // Output: https://new.com ``` -------------------------------- ### Usage Examples for Path Domain (aivi) Source: https://github.com/mendrik/aivi/blob/main/specs/stdlib/system/path.md Demonstrates practical usage of the Path domain and its associated functions. These examples illustrate how to build, manipulate, and query filesystem paths. ```aivi // Example of building a path let myPath = ~path["users", "docs", "file.txt"]; // Example of joining paths let anotherPath = myPath / "subdir"; // Example of using helper functions let parentDir = parent(myPath); let fileName = fileName(myPath); ``` -------------------------------- ### Usage Examples for Scheduler Domain Source: https://github.com/mendrik/aivi/blob/main/specs/stdlib/chronos/scheduler.md Demonstrates practical examples of how to use the Scheduler domain in various scenarios. This snippet provides concrete implementations for common tasks. ```aivi import aivi.chronos.scheduler // Example usage or definition from usage_examples.aivi ``` -------------------------------- ### AIVI Line Comments Example Source: https://github.com/mendrik/aivi/blob/main/specs/syntax/comments.md Demonstrates the usage of line comments in AIVI, which start with '//' and extend to the end of the line. These are useful for explaining code or temporarily disabling lines. ```aivi // This is a line comment let x = 5; // Assign 5 to x // let y = 10; // This line is commented out ``` -------------------------------- ### Instant Domain Usage Examples Source: https://github.com/mendrik/aivi/blob/main/specs/stdlib/chronos/instant.md Demonstrates practical usage of the Instant domain, showing how to create, manipulate, and compare instants. ```aivi use aivi.chronos.instant use aivi.chronos.duration // Get the current instant let now = instant.now() print("Current instant: ", now) // Create an instant from Unix timestamps let instant_from_seconds = instant.from_unix_seconds(1678886400) print("Instant from seconds: ", instant_from_seconds) let instant_from_milliseconds = instant.from_unix_milliseconds(1678886400123) print("Instant from milliseconds: ", instant_from_milliseconds) // Convert instants back to Unix timestamps let seconds = instant.to_unix_seconds(instant_from_seconds) print("Seconds since epoch: ", seconds) let milliseconds = instant.to_unix_milliseconds(instant_from_milliseconds) print("Milliseconds since epoch: ", milliseconds) // Perform duration arithmetic let one_hour = duration.new_hours(1) let future_instant = instant.add_duration(now, one_hour) print("Instant in one hour: ", future_instant) let past_instant = instant.subtract_duration(now, one_hour) print("Instant one hour ago: ", past_instant) // Calculate the difference between two instants let diff = instant.difference(past_instant, future_instant) print("Difference between instants: ", diff) // Compare instants let comparison_result = instant.compare(now, future_instant) print("Comparison of now and future_instant: ", comparison_result) // Should be -1 let comparison_equal = instant.compare(now, now) print("Comparison of now and now: ", comparison_equal) // Should be 0 ``` -------------------------------- ### Vector Usage Examples Source: https://github.com/mendrik/aivi/blob/main/specs/stdlib/math/vector.md Provides practical examples demonstrating how to use the Vector domain functions and operations. ```APIDOC ## Usage Examples This section contains code examples illustrating the usage of various functions and operations within the Vector domain. ``` -------------------------------- ### IMAP Email Fetch Example Source: https://github.com/mendrik/aivi/blob/main/specs/syntax/external_sources.md Illustrates fetching emails from an IMAP server using `Source.email.imap.fetch`. This example requires proper configuration of email server details. ```aivi Source.email.imap.fetch("imap.example.com", "user", "pass") ``` -------------------------------- ### Define a Resource with Setup, Yield, and Cleanup (Aivi) Source: https://github.com/mendrik/aivi/blob/main/specs/syntax/resources.md Demonstrates how to define a resource using a 'resource' block. This includes the setup phase before 'yield', yielding the acquired resource, and the cleanup phase that runs afterward. The cleanup code is guaranteed to execute when the resource goes out of scope. ```aivi resource { // Setup: Acquire the resource let handle = acquire_resource() // e.g., open a file // Yield the acquired resource to be used yield handle // Cleanup: Release the resource // This code runs when the resource goes out of scope release_resource(handle) // e.g., close the file } ``` -------------------------------- ### Install AIVI CLI with Cargo Source: https://github.com/mendrik/aivi/blob/main/README.md This snippet shows how to install the AIVI command-line interface (CLI) using Cargo, Rust's package manager. It assumes Rust is already installed on the system. After installation, you can run `aivi --help` to see available commands. ```bash cargo install --path crates/aivi aivi --help ``` -------------------------------- ### Database Query Example Source: https://github.com/mendrik/aivi/blob/main/specs/syntax/external_sources.md Provides an example of querying a database using `Source.db.query`. This snippet assumes a database connection and a defined query structure. ```aivi Source.db.query[User](sql"SELECT * FROM users WHERE id = ${userId}") ``` -------------------------------- ### Example Usage of aivi.ui.gtk4 Source: https://github.com/mendrik/aivi/blob/main/specs/stdlib/ui/gtk4.md This example demonstrates how to use the aivi.ui.gtk4 module to create a simple GTK4 application. It covers initialization, window creation, setting a title, and running the application event loop. ```aivi import aivi.ui.gtk4 // Initialize GTK4 aivi.ui.gtk4.init() // Create a new application let app = aivi.ui.gtk4.appNew("org.example.AiviGtk4App") // Create a new window let window = aivi.ui.gtk4.windowNew(app) aivi.ui.gtk4.windowSetTitle(window, "AIVI GTK4 App") // Show the window aivi.ui.gtk4.widgetShow(window) // Run the application aivi.ui.gtk4.appRun(app) ``` -------------------------------- ### Aivi Decorator Syntax Example Source: https://github.com/mendrik/aivi/blob/main/specs/syntax/decorators.md Demonstrates the basic syntax of decorators in Aivi, showing how they are placed before the binding they annotate. ```aivi syntax.aivi ``` -------------------------------- ### AIVI Project File Structure Example Source: https://github.com/mendrik/aivi/blob/main/specs/tools/packaging.md Illustrates the typical directory layout for an AIVI project, including configuration files, source entry points, and build artifacts. ```text my-project/ ├── aivi.toml # AIVI-specific configuration ├── Cargo.toml # Rust/Cargo configuration ├── src/ │ ├── main.aivi # Entry point (for binaries) │ └── lib.aivi # Entry point (for libraries) ├── .gitignore └── target/ # Build artifacts ``` -------------------------------- ### Matrix Usage Examples (aivi) Source: https://github.com/mendrik/aivi/blob/main/specs/stdlib/math/matrix.md Illustrates practical applications of the Matrix domain in aivi. These examples showcase how matrices are used for common transformations like rotation, scaling, and translation in 2D or 3D space. ```aivi use aivi.matrix use aivi.vector // Example: Creating a translation matrix let translation_matrix = ~mat 1 0 0 5 0 1 0 0 0 0 1 0 0 0 0 1 // Example: Applying transformation to a point (represented as Vec4) let point = Vec4(1.0, 2.0, 3.0, 1.0) let transformed_point = translation_matrix × point // Example: Combining transformations (e.g., rotation then translation) let rotation_matrix = ... // definition of a rotation matrix let combined_matrix = translation_matrix × rotation_matrix ``` -------------------------------- ### Graph Usage Examples Source: https://github.com/mendrik/aivi/blob/main/specs/stdlib/math/graph.md Demonstrates practical applications and usage patterns of the Graph domain. These examples illustrate how to leverage the defined functions and algorithms to solve real-world problems involving networks and relationships. ```aivi import "../stdlib/math/graph/usage_examples.aivi" ``` -------------------------------- ### Platform, Clipboard, and Intersection Effects Example Source: https://github.com/mendrik/aivi/blob/main/specs/stdlib/ui/server_html.md This example showcases advanced features of aivi.ui.ServerHtml, including handling platform-specific events (like visibility changes), interacting with the clipboard API, and implementing intersection observer effects for lazy loading or scroll-based interactions. It demonstrates how to integrate these capabilities into a server-rendered application. ```aivi pub fn effectsApp(req: Request) -> VNode Msg { html! {
Observe me
} } // ... message handlers for platform, clipboard, and intersection events ``` -------------------------------- ### Aivi: Partial Application Example Source: https://github.com/mendrik/aivi/blob/main/specs/syntax/functions.md Demonstrates partial application in Aivi, where a function is applied with some, but not all, of its arguments. This results in a new function that expects the remaining arguments. ```aivi add = (x, y) => x + y add_five = add 5 add_five 10 // => 15 ``` -------------------------------- ### Aivi Vector Usage Examples Source: https://github.com/mendrik/aivi/blob/main/specs/stdlib/math/vector.md Provides practical examples of how to use the Vector domain in Aivi for common tasks. This snippet demonstrates creating vectors, performing operations, and utilizing helper functions in a concise manner. ```aivi // Create vectors let position = vec3 10.0 20.0 5.0 let velocity = vec3 1.0 0.0 0.0 // Vector addition (e.g., updating position) let new_position = position + velocity * 0.5 // Move 0.5 units in the x-direction // Calculate distance between two points let point_a = vec2 1.0 1.0 let point_b = vec2 4.0 5.0 let dist_ab = distance point_a point_b // dist_ab is 5.0 // Normalize a direction vector let direction = vec3 2.0 2.0 0.0 let normalized_direction = normalize direction // normalized_direction is vec3 (1/sqrt(2)) (1/sqrt(2)) 0.0 // Linear interpolation between two vectors let start_color = vec3 1.0 0.0 0.0 // Red let end_color = vec3 0.0 0.0 1.0 // Blue let mid_color = lerp start_color end_color 0.5 // Purple ``` -------------------------------- ### Aivi: Higher-Order Functions Example Source: https://github.com/mendrik/aivi/blob/main/specs/syntax/functions.md Illustrates the concept of higher-order functions in Aivi, where functions can accept other functions as arguments or return functions. This example shows a function that applies another function to a value. ```aivi apply = (f, x) => f(x) square = x => x * x apply(square, 5) // => 25 ``` -------------------------------- ### Dijkstra's Shortest Paths Example with Loops in Aivi Source: https://github.com/mendrik/aivi/blob/main/specs/syntax/effects.md Provides a concrete example of implementing Dijkstra's shortest path algorithm using tail-recursive loops within a 'do Effect' block, showcasing stateful iteration for complex algorithms. ```aivi // Dijkstra's algorithm implementation using loop/recurse do // ... initialization ... loop state = initialState => if not converged(state) then nextState = computeNextState(state) recurse nextState else pure state ``` -------------------------------- ### S3 Object Fetch Example Source: https://github.com/mendrik/aivi/blob/main/specs/syntax/external_sources.md Illustrates fetching an object from an S3 bucket using `Source.s3.get`. This requires appropriate AWS credentials and bucket configuration. ```aivi Source.s3.get("my-bucket", "path/to/object.json") ``` -------------------------------- ### Concurrency Domain Example - aivi Source: https://github.com/mendrik/aivi/blob/main/specs/stdlib/system/concurrency.md Demonstrates the basic usage of the aivi concurrency domain, likely involving spawning fibers or using channels for communication. ```aivi use aivi.concurrency // Example usage of concurrency primitives like par, scope, or channels // This snippet is a placeholder for actual code from the documentation. // For instance, it might show how to run two effects in parallel: // Effect.par(Effect.succeed(1), Effect.succeed(2)).map(|(a, b)| a + b) ``` -------------------------------- ### Image Metadata Fetch Example Source: https://github.com/mendrik/aivi/blob/main/specs/syntax/external_sources.md Demonstrates fetching metadata for an image file using `Source.image.meta`. This allows access to image properties without loading the full pixel data. ```aivi Source.image.meta("path/to/image.jpg") ``` -------------------------------- ### Compile-Time Source Example Source: https://github.com/mendrik/aivi/blob/main/specs/syntax/external_sources.md Shows how to define and use a compile-time source, indicated by the `@static` annotation. These sources are embedded into the binary, ensuring zero latency and high reliability at runtime. ```aivi @static const config = Source.file.read("config.json") ``` -------------------------------- ### Writing an AIVI Library Entry Point (AIVI) Source: https://github.com/mendrik/aivi/blob/main/specs/runtime/package_manager.md Example of an AIVI library's entry point file. This demonstrates basic AIVI syntax for defining functions and exporting them from a library. ```aivi export fn greet(name: str) -> str { return "Hello, " + name + "!"; } ``` -------------------------------- ### Standard Library Prelude Example (aivi) Source: https://github.com/mendrik/aivi/blob/main/specs/stdlib/core/prelude.md Demonstrates the basic usage of the aivi.prelude, showcasing how core types and functions are automatically available for common operations like printing and basic arithmetic. ```aivi def main() { let message = "Hello, Prelude!"; print(message); let a = 5; let b = 10; let sum = a + b; print("Sum: " + toString(sum)); } ``` -------------------------------- ### Counter App Example with Route-Based Server Bootstrap Source: https://github.com/mendrik/aivi/blob/main/specs/stdlib/ui/server_html.md Demonstrates a basic counter application using aivi.ui.ServerHtml, showcasing route-based server bootstrapping. It illustrates how to set up an HTTP endpoint that serves the initial HTML and JavaScript, and how WebSocket connections are established for interactive updates. ```aivi pub fn counterApp(req: Request) -> VNode Msg { html! {

Counter

Count: {count}

} } let server = ServerHtml::new() .route("/counter", counterApp) .build(); // ... server startup logic ``` -------------------------------- ### HTTP GET Request Source: https://github.com/mendrik/aivi/blob/main/specs/stdlib/network/http.md Performs a GET request to the specified URL and returns the server's response. ```APIDOC ## GET /url ### Description Performs a GET request to the specified URL. ### Method GET ### Endpoint `/url` ### Parameters #### Path Parameters - **url** (Url) - Required - The URL to send the GET request to. ### Response #### Success Response (200) - **Response** (Response) - The server's response to the request. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Initialize New AIVI Project Source: https://github.com/mendrik/aivi/blob/main/specs/tools/cli.md Creates a new AIVI project in the specified directory. Options include creating a binary or library project, setting the Rust edition, and specifying the AIVI language version. The --force flag allows creation in a non-empty directory. ```bash aivi init [--bin|--lib] [--edition 2024] [--language-version 0.1] [--force] ``` -------------------------------- ### Building and Syncing the AIVI Server HTML Client Source: https://github.com/mendrik/aivi/blob/main/specs/stdlib/ui/server_html.md This section outlines the process for building the browser client-side JavaScript bundle for aivi.ui.ServerHtml and syncing it into the Rust runtime crates. It involves navigating to the 'ui-client' directory, installing dependencies, building the project, and executing a script to copy the generated bundle. ```bash cd ui-client pnpm install pnpm build node ./scripts/sync-to-rust.mjs ``` -------------------------------- ### Install cargo-bolero Source: https://github.com/mendrik/aivi/blob/main/fuzz/README.md Installs the cargo-bolero tool, which is a unified fuzzing and property-testing front-end. This command ensures the necessary tooling is available for running fuzz targets. ```bash cargo install -f cargo-bolero ``` -------------------------------- ### Predicate Lifting Example 5 (aivi) Source: https://github.com/mendrik/aivi/blob/main/specs/syntax/predicates.md Presents a final example of predicate lifting in aivi, emphasizing the transformation of predicate expressions into executable functions. ```aivi takeWhile _.status == "pending" ``` -------------------------------- ### Client Implementation and Embedding Source: https://github.com/mendrik/aivi/blob/main/specs/stdlib/ui/server_html.md Instructions on how to build and sync the browser client JavaScript bundle for use with ServerHtml. ```APIDOC ## Client Implementation and Embedding ### Building the Client The browser client is located in `ui-client/` and is built into a single IIFE bundle (`ui-client/dist/aivi-server-html-client.js`). To build: ```bash cd ui-client pnpm install pnpm build ``` ### Syncing to Rust Crates After building, sync the bundle to the runtime crates: ```bash node ./scripts/sync-to-rust.mjs ``` This copies the bundle to: - `crates/aivi/src/runtime/builtins/ui/server_html_client.js` - `crates/aivi_native_runtime/src/builtins/ui/server_html_client.js` ``` -------------------------------- ### Predicate Lifting Example 2 (aivi) Source: https://github.com/mendrik/aivi/blob/main/specs/syntax/predicates.md Provides an example of predicate lifting in aivi, showcasing how predicates can be automatically converted to functions that operate on individual elements. ```aivi filter _.name == "Alice" ``` -------------------------------- ### Module Documentation Example using Quick Info Markers Source: https://github.com/mendrik/aivi/blob/main/specs/doc-markers-spec.md Demonstrates how to use the quick-info markers to document a module. The opening marker contains JSON metadata specifying the kind and name of the module, followed by the markdown content that will be displayed as hover information. ```markdown The `aivi.text` module provides core string and character utilities for `Text` and `Char`. ``` -------------------------------- ### Opting Out of Prelude (aivi) Source: https://github.com/mendrik/aivi/blob/main/specs/stdlib/core/prelude.md Illustrates how to explicitly opt out of using the aivi.prelude module. This is useful for advanced use cases where fine-grained control over imported modules is necessary. ```aivi use aivi::core::prelude; // To opt out, you would typically avoid using prelude functions directly // or use a different module scope. This example assumes a context where // prelude is implicitly available but you want to be explicit about not using it. // Example of using a non-prelude type or function if available: // let custom_list = List::new(); ``` -------------------------------- ### Usage Examples for Duration Domain Source: https://github.com/mendrik/aivi/blob/main/specs/stdlib/chronos/duration.md This snippet provides practical examples of how to use the Duration domain in code. It demonstrates creating Duration objects, performing comparisons, and utilizing conversions. ```aivi use aivi.chronos.duration.Duration // Creating durations let timeout: Duration = 500ms let delay: Duration = 2s // Comparing durations if (timeout < delay) { print("Timeout is shorter than delay.") } // Using durations in functions function processWithTimeout(data: any, duration: Duration) { // ... process data with the given duration ... print("Processing with timeout of ", duration) } processWithTimeout({"key": "value"}, timeout) // Converting durations let delayInMs: Number = delay.toMilliseconds() print("Delay in milliseconds: ", delayInMs) ``` -------------------------------- ### Start HTTP Server (Aivi) Source: https://github.com/mendrik/aivi/blob/main/specs/stdlib/network/http_server.md Starts an HTTP server using the provided configuration and request handler. It returns a Server resource that manages the server's lifecycle. ```aivi import aivi.net.httpServer // Function signature: // listen: ServerConfig -> (Request -> Effect HttpError ServerReply) -> Resource Server // Example usage: let config = { port: 8080, host: "127.0.0.1" }; let handler = (req) => Ok(HttpReply.new(200, "OK")); // This would typically be used within a larger effectful context // let serverResource = httpServer.listen(config, handler); ``` -------------------------------- ### Install Dependencies and Compile Extension (Bash) Source: https://github.com/mendrik/aivi/blob/main/vscode/README.md Installs project dependencies using pnpm and compiles the VS Code extension. This is a prerequisite for launching the extension in a development host. ```bash cd vscode pnpm install pnpm run compile ``` -------------------------------- ### Implement Concise State Machines with Aivi Source: https://github.com/mendrik/aivi/blob/main/specs/syntax/pattern_matching.md Demonstrates the creation of concise state machines using Aivi's pattern matching. This approach simplifies state management and transitions. ```aivi concise_state_machines.aivi ``` -------------------------------- ### Complex Sum-Type Patching Example Source: https://github.com/mendrik/aivi/blob/main/specs/syntax/patching.md Provides an example of patching within complex sum-type structures. This demonstrates how to target and modify values nested within different variants of a union type. ```aivi type Result = { Ok: String } | { Err: Int }; let res: Result = { Ok: "Success" }; let patch = { Ok: "Operation Successful" }; let updatedRes = res <| patch; // updatedRes is { Ok: "Operation Successful" } ``` -------------------------------- ### File Source Reading Example Source: https://github.com/mendrik/aivi/blob/main/specs/syntax/external_sources.md Illustrates reading data from a local file using the `Source.file.read` function. This is a basic example of accessing local file system resources within AIVI. ```aivi Source.file.read("my_data.json") ``` -------------------------------- ### Instant Domain Overview Source: https://github.com/mendrik/aivi/blob/main/specs/stdlib/chronos/instant.md Provides an overview of the Instant domain, explaining its purpose and how it represents a specific moment in time. ```aivi module instant { // Represents a specific moment in time, independent of time zones or calendars. // Corresponds to a UTC timestamp (Unix epoch). // Example: instant.now() // Get the current instant func now() -> Instant // Create an instant from a Unix timestamp (seconds since epoch) func from_unix_seconds(seconds: Int64) -> Instant // Create an instant from a Unix timestamp (milliseconds since epoch) func from_unix_milliseconds(milliseconds: Int64) -> Instant // Convert an instant to a Unix timestamp (seconds since epoch) func to_unix_seconds(instant: Instant) -> Int64 // Convert an instant to a Unix timestamp (milliseconds since epoch) func to_unix_milliseconds(instant: Instant) -> Int64 // Add a duration to an instant func add_duration(instant: Instant, duration: Duration) -> Instant // Subtract a duration from an instant func subtract_duration(instant: Instant, duration: Duration) -> Instant // Calculate the difference between two instants as a duration func difference(start: Instant, end: Instant) -> Duration // Compare two instants // Returns -1 if start < end, 0 if start == end, 1 if start > end func compare(start: Instant, end: Instant) -> Int } // Alias for Duration type from aivi.chronos.duration alias Duration = duration.Duration // Alias for Instant type alias Instant = instant.Instant ``` -------------------------------- ### Aivi Classes and HKTs Examples Source: https://github.com/mendrik/aivi/blob/main/specs/syntax/types/classes_and_hkts.md Demonstrates the fundamental syntax and usage of classes and higher-kinded types (HKTs) in Aivi. These examples showcase how to define and utilize generic types and their instances. ```aivi class Id[T] { def apply(x: T): T } object Id { given idInt: Id[Int] with { def apply(x: Int): Int = x } given idString: Id[String] with { def apply(x: String): String = x } } def identity[T](x: T)(using id: Id[T]): T = id.apply(x) identity(10) identity("hello") ``` ```aivi class Functor[F[_]] { def map[A, B](fa: F[A], f: A => B): F[B] } object ListFunctor extends Functor[List] { def map[A, B](fa: List[A], f: A => B): List[B] = fa.map(f) } def fmap[F[_], A, B](fa: F[A], f: A => B)(using functor: Functor[F]): F[B] = functor.map(fa, f) fmap(List(1, 2, 3), (x: Int) => x * 2) ``` ```aivi class Monad[M[_]] extends Functor[M] { def pure[A](a: A): M[A] def flatMap[A, B](ma: M[A], f: A => M[B]): M[B] // Functor's map can be defined in terms of flatMap def map[A, B](fa: M[A], f: A => B): M[B] = flatMap(fa, (a: A) => pure(f(a))) } object OptionMonad extends Monad[Option] { def pure[A](a: A): Option[A] = Some(a) def flatMap[A, B](ma: Option[A], f: A => Option[B]): Option[B] = ma.flatMap(f) } def unit[M[_], A](a: A)(using monad: Monad[M]): M[A] = monad.pure(a) def bind[M[_], A, B](ma: M[A], f: A => M[B])(using monad: Monad[M]): M[B] = monad.flatMap(ma, f) bind(Some(5), (x: Int) => Some(x * 2)) bind(None, (x: Int) => Some(x * 2)) ``` ```aivi class Foldable[T[_]] { def foldRight[A, B](ta: T[A], z: B, f: (A, B) => B): B } object ListFoldable extends Foldable[List] { def foldRight[A, B](ta: List[A], z: B, f: (A, B) => B): B = ta.foldRight(z)(f) } def foldr[T[_], A, B](ta: T[A], z: B, f: (A, B) => B)(using foldable: Foldable[T]): B = foldable.foldRight(ta, z, f) foldr(List(1, 2, 3), 0, (x: Int, acc: Int) => x + acc) ``` ```aivi class Show[T] { def apply(t: T): String } object IntShow extends Show[Int] { def apply(t: Int): String = t.toString } object StringShow extends Show[String] { def apply(t: String): String = t } def print[T](t: T)(using s: Show[T]): String = s.apply(t) print(123) print("hello") ``` -------------------------------- ### Usage Examples for Calendar Domain Source: https://github.com/mendrik/aivi/blob/main/specs/stdlib/chronos/calendar.md This snippet demonstrates practical usage of the Calendar domain's functions. It provides concrete examples of how to leverage the domain for common date and time-related tasks. ```aivi /* Example 1: Adding months to a date let today = Date.now(); let nextMonth = addMonths(today, 1); print(`Today: ${today}, Next Month: ${nextMonth}`); Example 2: Checking for leap year let year = 2024; if (isLeapYear(Date.from({ year: year }))) print(`${year} is a leap year.`); */ ``` -------------------------------- ### aivi Color Short Constructor Source: https://github.com/mendrik/aivi/blob/main/specs/stdlib/ui/color.md Demonstrates the short constructor for creating RGB colors in the aivi domain. It shows the `rgb r g b` syntax and its equivalent representation as a record. ```aivi // Using the short constructor for RGB let red = rgb(255, 0, 0) // Equivalent record representation let redEquivalent = { r: 255, g: 0, b: 0 } print(red) print(redEquivalent) ``` -------------------------------- ### LLM Source Integration Example Source: https://github.com/mendrik/aivi/blob/main/specs/syntax/external_sources.md Shows how Large Language Models are treated as typed probabilistic sources in AIVI. This is a conceptual example highlighting AIVI's vision for intelligent data pipelines. ```aivi Source.llm.generate[Completion]("Translate the following text: ...") ``` -------------------------------- ### Build AIVI ServerHtml Client with pnpm Source: https://github.com/mendrik/aivi/blob/main/ui-client/README.md Instructions to build the AIVI ServerHtml client using pnpm. This involves navigating to the client directory, installing dependencies, and running the build command. The output is a single IIFE bundle. ```bash cd ui-client pnpm install pnpm build ``` -------------------------------- ### Aivi Runtime Configuration Example Source: https://github.com/mendrik/aivi/blob/main/specs/syntax/modules.md This Aivi code snippet demonstrates how to load runtime configuration values from environment variables. It's useful for managing settings like API URLs or database credentials that vary across different deployment environments without modifying the codebase. ```aivi import "std::env"; let db_password = env::get("DB_PASSWORD"); let api_url = env::get("API_URL"); // Use db_password and api_url in your application logic println("Database Password: {}", db_password); println("API URL: {}", api_url); ``` -------------------------------- ### Aivi Simple Color Domain Example Source: https://github.com/mendrik/aivi/blob/main/specs/syntax/domains.md Provides a practical example of defining a simple 'Color' domain in Aivi. This domain encapsulates Rgb color types and operations like adjusting lightness. ```aivi domain Color { carrier Rgb delta Lightness operators { (+) (x: Rgb, y: Lightness) -> Rgb } } use aivi.color (domain Color) let red = Rgb(255, 0, 0) let darker_red = red + 10l ``` -------------------------------- ### Aivi Idioms for Option and Result Handling Source: https://github.com/mendrik/aivi/blob/main/AIVI_LANGUAGE.md Illustrates Aivi's concise syntax for handling `Option` and `Result` types. It shows how to provide default values for `Option` types and how to pattern match on `Result` to handle success (`Ok`) or error (`Err`) cases. ```aivi opt match | Some x => x | None => default res match | Ok x => x | Err e => handle e opt ?? default ``` -------------------------------- ### Looping Constructs (Functional/Recursive) Source: https://github.com/mendrik/aivi/blob/main/AIVI_LANGUAGE.md Illustrates how to replace 'while' loops with recursion or generator-based looping mechanisms. ```functional # Anti-pattern: while cond { ... } # Corrected: Recursion or loop/recurse in generators ``` -------------------------------- ### Handle transition failures and state updates (Aivi) Source: https://github.com/mendrik/aivi/blob/main/specs/syntax/machines_runtime.md Illustrates a full machine flow example within a do Effect block. It includes registering an 'on' handler for the 'run' transition that intentionally fails, performing a 'lease' transition, attempting the 'run' transition to trigger the handler failure, and asserting the machine's state. ```aivi machineFlow = do Effect { { run, lease, currentState } = AccountSyncMachine on run => fail "run handler failure" _ <- lease {} runResult <- attempt (run { batchId: 1 }) _ <- runResult match | Err _ => pure Unit | Ok _ => fail "expected handler failure" _ <- assertEq (constructorName (currentState Unit)) "Syncing" pure Unit } ``` -------------------------------- ### Aivi Domain Usage Example Source: https://github.com/mendrik/aivi/blob/main/AIVI_LANGUAGE.md An example of using a domain in Aivi. This snippet shows a `Duration` domain being used to add a time value to a deadline, demonstrating how domains resolve operator semantics for non-Int types. ```aivi use aivi.chronos.duration (domain Duration) deadline = { millis: 0 } + 10min // + resolved by Duration domain ``` -------------------------------- ### Implicit Binding Rule Examples (aivi) Source: https://github.com/mendrik/aivi/blob/main/specs/syntax/predicates.md Shows examples of the implicit binding rule in aivi predicates, where '_' binds to the current element and bare field names resolve to _.field. This simplifies access to fields within predicate expressions. ```aivi filter active filter _.active filter .active ``` -------------------------------- ### Architecture and Workflow Source: https://github.com/mendrik/aivi/blob/main/specs/stdlib/ui/server_html.md Illustrates the communication flow between the browser and server for rendering and interaction. ```APIDOC ## Architecture ### Workflow Diagram ```mermaid sequenceDiagram participant Browser participant Server Browser->>Server: HTTP GET /counter Note over Browser,Server: HTML + boot blob + JS Server-->>Browser: Initial render payload Browser->>Server: WS connect /counter/ws Browser->>Server: hello(viewId, url, online) Browser->>Server: event/platform/effectResult Server-->>Browser: patch/effectReq/error ``` ### Notes - HTTP paths are normalized (e.g., `/counter/` works). - WebSocket paths are derived as `//ws` (e.g., `/counter/ws`). - Unknown paths result in a `404` response. ``` -------------------------------- ### AIVI Units Domain Usage Examples Source: https://github.com/mendrik/aivi/blob/main/specs/stdlib/core/units.md Provides practical examples of how to use the AIVI Units domain in real-world scenarios. This snippet showcases defining quantities with units, performing calculations, and leveraging the domain's safety features. ```aivi // Example: Calculating force (Mass * Acceleration) let mass: Kilograms = 10.0 let acceleration: Meters / Seconds^2 = 5.0 let force: Newtons = mass * acceleration // Newtons is implicitly Kilograms * Meters / Seconds^2 // Example: Working with different units for the same dimension let length_m: Meters = 100.0 let length_ft: Feet = convert(length_m, Feet) // Example: Invalid operation caught at compile time // let invalid_addition = length_m + time // Example: Using defined units in function signatures function calculate_work(force: Newtons, distance: Meters): Joules { return force * distance } ``` -------------------------------- ### Define and Apply Functions in Aivi Source: https://github.com/mendrik/aivi/blob/main/AIVI_LANGUAGE.md Demonstrates defining curried functions and applying them with whitespace. Includes partial application using function currying. ```aivi add : Int -> Int -> Int add = a b => a + b result = add 5 10 // 15 inc = add 1 // partial application ``` -------------------------------- ### Aivi Suffix Literal Usage Source: https://github.com/mendrik/aivi/blob/main/AIVI_LANGUAGE.md Examples of Aivi suffix literals, which are numeric literals followed by a suffix identifier. These resolve to domain-defined template functions. Examples include time durations, pixel values, percentages, and weeks. ```aivi 10min 30s 100px 50% 2w 3d ``` -------------------------------- ### Install Dependencies and Build Extension Package (Bash) Source: https://github.com/mendrik/aivi/blob/main/vscode/README.md Installs project dependencies using pnpm and builds the AIVI VS Code extension into a .vsix package. This command also rebuilds the aivi-lsp and regenerates syntax highlighting files. ```bash cd vscode pnpm install pnpm run build ``` -------------------------------- ### Install AIVI Project Dependency Source: https://github.com/mendrik/aivi/blob/main/specs/tools/cli.md Installs a dependency into the current AIVI project. Dependencies can be specified by name, name@version, Git URL, or local path. Validation ensures dependencies meet AIVI's requirements, including language version and kind. ```bash aivi install [--no-fetch] ``` -------------------------------- ### HTTP GET Request with aivi.net.http Source: https://github.com/mendrik/aivi/blob/main/specs/stdlib/network/http.md Performs an HTTP GET request to a specified URL. It returns an `Effect` that, upon execution, yields either an `HttpError` or a `Response` object containing the server's reply. This function is a fundamental part of interacting with web resources. ```aivi def get(url: Url) -> Effect HttpError Response { fetch(Request { method: "GET", url: url, headers: [], body: None }) } ```