std
Standard libraries for the foundation ecosystem.
Core utilities, concurrency, JVM tooling, integrations, and focused API references.
Library families
Start with a family overview, then follow its focused pages and walkthroughs.
std.concurrent
Queues, executors, requests, relays, pools, and threads.
jvm.*
Artifacts, classloaders, namespaces, reflection, monitoring, and tools.
lib.*
Databases, containers, search, messaging, storage, and repositories.
std.dispatch
Boards, hubs, queues, debounce, hooks, and dispatch core.
std.fs
Paths, walking, archives, attributes, and watchers.
std.scheduler
Runners, programs, spawns, and scheduled task lifecycle.
std.string
Case, coercion, paths, pluralization, prose, and wrapping.
std.task
Process and bulk task execution.
std.time
Time coercion, durations, zones, formats, and representations.
std.timeseries
Journals, intervals, ranges, computation, and processing.
std.block
Code representation, traversal, and manipulation.
std.lib
Focused foundational utilities.
std.lib.apply
Applicative invocation and host applicatives.
std.lib.atom
Nested atoms, batch updates, cursors, and derived state.
std.lib.bin
Binary data, buffers, and low-level data handling.
std.lib.class
Class, type, and reflection helpers.
std.lib.collection
Extended map, sequence, tree, and diff operations.
std.lib.component
Component lifecycle and system composition primitives.
std.lib.encode
Encoding and decoding helpers.
std.lib.enum
Enum and lookup helpers.
std.lib.env
Namespace, resource, pprint, and debug utilities.
std.lib.foundation
Basic predicates, constructors, and helpers.
std.lib.future
Future and asynchronous coordination helpers.
std.lib.io
I/O helpers and stream handling.
std.lib.network
Network and port utilities.
std.lib.resource
Classpath and filesystem resource helpers.
std.lib.schema
Schema definitions, lookups, and validation helpers.
std.lib.security
Security, keys, providers, ciphers, and verification helpers.
std.lib.sort
Sorting, ordering, and topological utilities.
std.lib.stream
Producers, collectors, pipelines, and transducers.
std.lib.system
System topology, display, and lifecycle utilities.
std.lib.time
Time coercion and temporal helpers.
std.lib.transform
Composable data transformation helpers.
std.lib.walk
Walking and traversal helpers.
std.lib.zip
Zipper navigation and editing helpers.
1 Walkthrough
The std section is organized into library families. Most workflows start by requiring the top-level namespace, then drilling into sub-namespaces for specialised behaviour.
a cross-library snippet: string case, collection transform, and time coercion
(require '[std.string :as str]
'[std.lib.collection :as coll]
'[std.time :as time])
(->> {"hello-world" 1 "hello-there" 2}
(coll/map-keys str/camel-case)
(coll/map-vals inc))
=> {"helloWorld" 2 "helloThere" 3}
(time/to-ms 1 :m)
=> 60000
2 std.config: A Comprehensive Summary (including submodules)
The std.config module provides a powerful and flexible configuration management system for Clojure applications. It allows for defining configurations using a rich set of directives, resolving values from various sources (system properties, environment variables, project files, external files, resources), and handling sensitive data through encryption. The system is designed to be extensible, supporting different configuration formats (EDN, JSON, YAML, TOML) and secure key management (GPG).
2.1 std.config (Main Namespace)
This namespace serves as the primary entry point for the configuration system, aggregating and re-exporting key functionalities from its submodules. It defines the core directives and option types that drive the configuration resolution process.
Key Re-exported Functions:
- From
std.config.global:global.n Fromstd.config.resolve:load,resolve,resolve-key,encrypt-text,decrypt-text.n Fromstd.config.secure:resolve-key,encrypt-text,decrypt-text.
Core Concepts:
- Directives: Special vector forms (e.g.,
[:env "VAR_NAME"],[:file "path/to/file"]) that instruct the configuration system how to resolve a value.n Option Keys: Metadata associated with configuration values (e.g.,:type,:secured,:key,:default).n Option Types: Supported data types for resolved content (e.g.,:text,:edn,:json,:yaml,:gpg,:gpg.public).
Key Functions:
get-session,swap-session,clear-session: Functions for interacting with the global session atom, which can store dynamic configuration values.n+directives+: A list of all supported configuration directives.n+opt-keys+: A list of supported option keys for configuration values.n*+opt-types+: A list of supported types for resolving configuration content.
2.2 std.config.common (Common Utilities and Multimethods)
This sub-namespace defines common multimethods that serve as extension points for resolving directives and handling different content types.
Key Functions:
-resolve-directive(multimethod): The primary extension point for implementing new configuration directives. It dispatches based on the first element of a directive vector.n*-resolve-type(multimethod): The primary extension point for handling different content types during resolution (e.g., parsing JSON, YAML).
2.3 std.config.ext.gpg (GPG Integration)
This sub-namespace provides integration with GPG (GNU Privacy Guard) for handling encrypted configuration values.
Key Functions:
resolve-type-gpg-public: Resolves content to a PGP public key (org.bouncycastle.openpgp.PGPPublicKey).n*resolve-type-gpg: Resolves content to a PGP key pair (public and private keys).
2.4 std.config.ext.json (JSON Integration)
This sub-namespace provides support for resolving configuration values from JSON content.
Key Functions:
resolve-type-json: Resolves JSON content into a Clojure map (with keywordized keys).
2.5 std.config.ext.toml (TOML Integration)
This sub-namespace provides support for resolving configuration values from TOML content.
Key Functions:
resolve-type-toml: Resolves TOML content into a Clojure map (with keywordized keys).
2.6 std.config.ext.yaml (YAML Integration)
This sub-namespace provides support for resolving configuration values from YAML content.
Key Functions:
resolve-type-yaml: Resolves YAML content into a Clojure map.
2.7 std.config.global (Global Configuration Sources)
This sub-namespace provides functions for accessing and consolidating configuration values from various global sources, such as system properties, environment variables, project files, and user home directory files.
Core Concepts:
+session+: An atom for storing dynamic, session-specific configuration.n+cache: An atom for caching resolved global configuration values.nGlobalrecord: A record type for representing consolidated global configuration.
Key Functions:
global?: Checks if an object is aGlobalrecord.nglobal-raw: Constructs aGlobalrecord from a map, applying a key transformation function.nglobal-env-raw: Retrieves system environment variables as aGlobalrecord.nglobal-properties-raw: Retrieves system properties as aGlobalrecord.nglobal-project-raw: Retrieves project configuration (fromcode.project) as aGlobalrecord.nglobal-env-file-raw: Reads configuration from anenv.ednfile in the current directory.nglobal-home-raw: Reads configuration from aglobal.ednfile in the user's.haradirectory.nglobal-session-raw: Retrieves the current session configuration.nglobal-all-raw: Consolidates all global configuration sources into a singleGlobalrecord.n*global: The primary function for retrieving global configuration from a specified source (e.g.,:env,:properties,:project,:all), with optional caching.
2.8 std.config.resolve (Directive Resolution Engine)
This sub-namespace implements the core logic for resolving configuration directives and content from various sources. It uses a recursive prewalk approach to process nested directives.
Core Concepts:
- Directive Resolution: Directives are processed recursively, allowing for complex, dynamic configuration.n Path Tracking:
*current*and*path*dynamic vars track the current resolution context for error reporting.n Error Handling: Providesex-configfor creating informative exceptions during resolution.
Key Functions:
ex-config: Creates a configuration-specific exception.nwalk,prewalk: Modified versions ofclojure.walkfunctions for directive resolution.ndirective?: Checks if a form is a configuration directive.nresolve-directive: Resolves a single directive, handling errors.nresolve: The main function for resolving a configuration form, recursively processing all directives. It can also bind a security key for decryption.nresolve-type: Dispatches tocommon/-resolve-typeto convert content to a specific type (e.g.,:edn,:json).nresolve-select: Selects specific keys or paths from resolved content.nresolve-content: Resolves content based on options like:type,:secured,:key,:default,:select.nresolve-directive-properties: Resolves values from system properties.nresolve-directive-env: Resolves values from environment variables.nresolve-directive-project: Resolves values from project metadata.nresolve-directive-format: Formats values into a string usingclojure.core/format.nresolve-directive-str: Joins values into a string.nresolve-directive-or: Returns the first non-nil resolved value from a list of options.nresolve-directive-case: Implements acasestatement for configuration values.nresolve-directive-error: Throws a configuration error.nresolve-directive-merge: Merges multiple configuration maps, supporting different merge strategies (:default,:nil,:nested,:nested-nil).nresolve-directive-eval: Evaluates a Clojure form within the configuration context.nresolve-map: Resolves values from a map using a path.nresolve-directive-root: Resolves a directive relative to the root of the current configuration.nresolve-directive-parent: Resolves a directive relative to the parent of the current configuration.nresolve-directive-global: Resolves a directive from the global configuration map.nresolve-path: Resolves a path string.nresolve-directive-file: Resolves content from a local file.nresolve-directive-resource: Resolves content from a classpath resource.nresolve-directive-include: Resolves content from a file or resource, searching in multiple locations.nload: Loads and resolves a configuration file (defaults toconfig.edn).
2.9 std.config.secure (Secure Configuration)
This sub-namespace provides functionalities for encrypting and decrypting sensitive configuration values, typically using AES encryption.
Core Concepts:
- Master Key: Uses a master key (from
+master-key+or*key*dynamic var) for encryption/decryption.n Key Resolution:resolve-keyhandles various key formats (string, map,java.security.Key).n Encryption/Decryption: Leveragesstd.lib.securityfor cryptographic operations andstd.lib.encodefor Base64/hex encoding.
Key Functions:
+master-key+: The default master key, typically loaded from global configuration.n+master-defaults+: Default settings for the encryption algorithm (AES, RAW format, secret mode).n*key*: A dynamic var holding the currently active security key.nresolve-key: Resolves a key from various inputs into ajava.security.Keyobject.ndecrypt-text: Decrypts an encrypted string (Base64 or hex encoded) using a specified key.n*encrypt-text: Encrypts a plain text string and returns its Base64 or hex encoded representation.
2.10 Usage Pattern:
The std.config module is essential for managing application configurations in a flexible, dynamic, and secure manner. It's particularly useful for:
- Environment-Specific Configurations: Easily switching configurations based on deployment environment (dev, test, prod).n Sensitive Data Handling: Storing API keys, passwords, and other secrets securely.n Modular Configuration: Breaking down large configurations into smaller, manageable files.n Dynamic Value Resolution: Resolving values from various runtime sources (environment, system properties).n Extensible Formats: Supporting different configuration file formats.
By providing a powerful and extensible configuration system, std.config enables developers to build applications that are easily configurable and adaptable to different operational contexts.
3 std.contract: A Comprehensive Summary (including submodules)
The std.contract module provides a powerful and flexible system for defining and enforcing contracts (schemas) for data and functions in Clojure applications. Built on top of the Malli library, it offers a declarative way to specify data shapes, validate inputs and outputs, and ensure type safety. This module is crucial for improving code reliability, maintainability, and for facilitating robust API design.
3.1 std.contract (Main Namespace)
This namespace serves as the primary entry point for the contract system, aggregating and re-exporting key functionalities from its submodules. It provides a high-level interface for defining and working with contracts.
Key Re-exported Functions:
- From
std.contract.sketch:maybe,opt,fn,lax,opened,tighten,closed,norm,remove,as:sketch,as:schema.n Fromstd.contract.type:defcase,defmultispec,defspec,spec?,common-spec,multi-spec,valid?.n Fromstd.contract.binding:defcontract.n* Frommalli.core:schema,schema?.
3.2 std.contract.sketch (Schema Sketching and Transformation)
This sub-namespace provides utilities for creating and transforming Malli schemas, offering a more convenient and expressive way to define data shapes. It introduces concepts like optional keys and nullable values directly into the schema definition process.
Core Concepts:
- Optional (
Optionalrecord): Represents a key that may or may not be present in a map.n Maybe (Mayberecord): Represents a value that can benil.n Func (Funcrecord): Represents a function schema, allowing validation of function arity or other properties.n* Schema Transformations: Functions to modify schemas, such as making keys optional, values nullable, or closing/opening map schemas.
Key Functions:
optional-string,maybe-string: String representations forOptionalandMayberecords.nas:optional: Creates anOptionalrecord for a key.noptional?: Checks if an object is anOptionalrecord.nas:maybe: Creates aMayberecord for a value.nmaybe?: Checks if an object is aMayberecord.nfunc-string,func-invoke: String representation and invocation forFuncrecords.nfn-sym: Extracts the symbol from a function.nfunc-form,func(macro): Creates aFuncrecord from a function form.nfunc?: Checks if an object is aFuncrecord.nfrom-schema-map: Converts a Malli AST map representation into a sketch (Clojure map withOptional/Mayberecords).nfrom-schema: Converts a Malli schema into a sketch.nto-schema-extend(multimethod): An extension point for converting custom types to Malli schemas.nto-schema: Converts a sketch or other Clojure data into a Malli schema.nlax: Transforms a map schema to make all keys optional and all values nullable (maybe).nnorm: Transforms a map schema to make all keys required (removes optionality).nclosed: Closes a map schema, disallowing extra keys.nopened: Opens a map schema, allowing extra keys.ntighten: Transforms a map schema to make all keys required and all values non-nullable (removesmaybe).nremove: Removes keys from a map schema.
3.3 std.contract.type (Contract Definition and Validation)
This sub-namespace provides the core mechanisms for defining and validating data against schemas. It introduces CommonSpec for single schemas and MultiSpec for multimethod-like schema dispatch.
Core Concepts:
CommonSpec: A record that wraps a single Malli schema, providing methods for validation and introspection.nMultiSpec: A record that manages multiple schemas, dispatching to the appropriate one based on a dispatch function, similar todefmulti.n Schema Validation: Uses Malli'svalidateandexplainfunctions for robust data validation.
Key Functions:
check: Validates data against a schema and throws an informative exception if invalid.ncommon-spec-invoke,common-spec-string: Invocation and string representation forCommonSpec.ncombine: Merges multiple schemas (typically map schemas).ncommon-spec: Creates aCommonSpecfrom one or more sketches/schemas.ndefspec(macro): Defines a namedCommonSpec.nmulti-spec-invoke,multi-spec-string: Invocation and string representation forMultiSpec.nmulti-gen-final: Generates the final Malli schema for aMultiSpec.nmulti-spec-add: Adds a new case (dispatch value and schema) to aMultiSpec.nmulti-spec-remove: Removes a case from aMultiSpec.nmulti-spec: Creates aMultiSpecfrom a dispatch function and a map of cases.ndefmultispec(macro): Defines a namedMultiSpec.ndefcase(macro): Adds a case to an existingMultiSpec.nspec?: Checks if an object is aCommonSpecorMultiSpec.n*valid?: Checks if data is valid against a spec, returningtrueorfalse.
3.4 std.contract.binding (Function Contract Binding)
This sub-namespace provides a mechanism to bind contracts directly to functions, enabling automatic input and output validation when the function is invoked.
Core Concepts:
Contractrecord: Encapsulates a function, its input schemas, and its output schema.n* Function Interception: When a contract is bound to a var, the contract itself becomes the var's value, intercepting calls to perform validation.
Key Functions:
contract-info: Returns information about a contract.ncontract-invoke: Invokes the underlying function of a contract, performing input and output validation.ncontract-string: String representation forContract.nContract(defimpl record): The concrete record type for a function contract.ncontract?: Checks if an object is aContractrecord.ncontract-var?: Checks if a var's value is aContract.nbound?: Checks if a contract is currently bound to its target var.nunbind: Removes a contract from a var, restoring the original function.nbind: Binds a contract to a var, replacing the original function with the contract.nparse-arg: Parses an input/output argument definition into a spec and options.ncontract: Creates aContractrecord.n*defcontract(macro): Defines a contract and binds it to a function var, enabling automatic validation.
3.5 Usage Pattern:
The std.contract module is invaluable for:
- API Design and Enforcement: Clearly defining the expected structure of data for APIs and ensuring adherence.n Robustness: Catching data inconsistencies and invalid inputs early, preventing bugs.n Documentation: Schemas serve as living documentation for data structures.n Code Clarity: Making explicit the assumptions about data shapes.n Metaprogramming: Programmatically generating and manipulating schemas.n* Test-Driven Development: Writing tests that validate data against contracts.
By integrating Malli and providing a Clojure-idiomatic way to define and enforce contracts, std.contract significantly enhances the reliability and maintainability of foundation-base applications.
4 std.dom: A Comprehensive Summary (including submodules)
The std.dom module provides a powerful and flexible framework for building and managing user interfaces (UIs) in Clojure, inspired by concepts from React and other declarative UI libraries. It introduces a "code-as-data" approach to UI definition, allowing developers to describe UI structures as Clojure data (DOMs) which can then be rendered, updated, and manipulated efficiently. The module supports component-based development, local state management, reactive updates, and a robust diffing/patching mechanism for optimized UI rendering.
4.1 std.dom (Main Namespace)
This namespace serves as the primary entry point for the DOM system, aggregating and re-exporting key functionalities from its submodules. It provides a high-level interface for creating, manipulating, and interacting with DOM structures.
Key Re-exported Functions:
- From
std.dom.common:dom-attach,dom-children,dom-compile,dom-create,dom-detach,dom-item,dom-item?,dom-equal?,dom-metaclass,dom-metaprops,dom-metatype,dom-split-props,dom-top,dom-trigger,dom-vector?,dom?,dom-assert.n Fromstd.dom.component:defcomp,dom-state-handler.n Fromstd.dom.diff:dom-diff,dom-ops.n Fromstd.dom.event:event-handler,handle-event.n Fromstd.dom.find:dom-match?,dom-find,dom-find-all.n Fromstd.dom.impl:dom-init,dom-remove,dom-render,dom-rendered,dom-replace.n Fromstd.dom.item:item-constructor,item-setters,item-getters,item-access,item-create,item-props-set,item-props-delete,item-update,item-cleanup.n Fromstd.dom.local:local,local-dom,local-dom-state,local-parent,local-parent-state,dom-send-local,dom-set-local.n Fromstd.dom.react:react,dom-set-state.n Fromstd.dom.type:metaclass,metaclass-add,metaclass-remove,metaprops,metaprops-add,metaprops-remove,metaprops-install.n Fromstd.dom.update:dom-apply,dom-update.
4.2 std.dom.common (Core DOM Structure and Utilities)
This sub-namespace defines the fundamental Dom record, its properties, and common operations for creating, formatting, and comparing DOM nodes.
Core Concepts:
DomRecord: The central data structure representing a UI node. It containstag,props,item(the actual rendered UI element),parent,handler,shadow(for components),cache, andextrametadata.n Metaclass/Metatype/Metaprops: A system for classifying and describing different types of UI elements (e.g.,:dom/element,:dom/component,:dom/value).n DOM Tree: DOM nodes form a tree structure, withparentand implicit child relationships.
Key Functions:
dom?: Checks if an object is aDomrecord.ndom-metaprops,dom-metatype,dom-metaclass: Accessors for metadata about a DOM node's type.ncomponent?,element?,value?: Predicates for checking the metatype of a DOM node.ndom-item,dom-item?: Accessors for the actual rendered UI element associated with a DOM node.ndom-top: Returns the top-most ancestor of a DOM node.ndom-split-props: Splits properties into different categories (e.g., event handlers, regular props).nprops-apply: Applies a function to properties, potentially recursing into nested DOMs.ndom-new: Creates a newDomrecord.ndom-children,children->props: Functions for managing children within DOM props.ndom-create: Creates aDomrecord from a tag, props, and children.ndom-format: Formats aDomrecord for printing (e.g.,[:- :tag {:prop val} child]).ndom-tags-equal?,dom-props-equal?,dom-equal?: Functions for comparing DOM nodes.ndom-clone: Creates a shallow copy of a DOM node.ndom-vector?: Checks if a vector represents a valid DOM structure.ndom-compile: Compiles a nested vector structure into a tree ofDomrecords.ndom-attach,dom-detach: Attaches or detaches an event handler to a DOM node.ndom-trigger: Triggers an event, propagating it up the DOM hierarchy.n*dom-assert: Asserts that required properties are present.
4.3 std.dom.component (Component-Based Development)
This sub-namespace provides the foundation for defining reusable UI components, supporting different component types (static, local, reactive) and lifecycle hooks.
Core Concepts:
- Component Types:
:static(purely functional, no internal state),:local(manages local state),:react(reactive to external state changes).n Lifecycle Hooks:pre-render,post-render,pre-update,post-update,pre-remove,post-remove,wrap-template.n Shadow DOM: Components maintain a "shadow DOM" (:shadowfield) which is their rendered output, allowing for efficient diffing.
Key Functions:
dom-component?: Checks if a DOM node represents a component.ncomponent-options: Prepares component options by merging mixins and template functions.ncomponent-install: Installs a component definition into themetapropsregistry.ndefcomp(macro): Defines a new UI component.ndom-render-component: Renders a component, executing its template and rendering its shadow DOM.nchild-components: Collects child components within a DOM tree.ndom-remove-component: Removes a rendered component.ndom-ops-component: Generates diff operations for components.ndom-apply-component: Applies diff operations to a component.ndom-replace-component: Replaces a component with a new one.ndom-state-handler: A generic handler for updating component local state.
4.4 std.dom.diff (DOM Diffing Algorithm)
This sub-namespace implements a diffing algorithm to efficiently compare two DOM trees and generate a minimal set of operations (an "edit script") to transform one into the other. This is crucial for optimizing UI updates.
Core Concepts:
- Edit Script: A list of operations (e.g.,
[:set key new-val old-val],[:delete key old-val],[:update key ops],[:list-insert index items],[:list-remove index count],[:replace new-dom old-dom]).n* Keyed Lists: Supports diffing lists of DOMs using a:dom/keyproperty for efficient element tracking.
Key Functions:
dom-ops(multimethod): Generates diff operations for a given tag and old/new properties.ndiff-list-element: Diffs individual elements within a list.ndiff-list-elements: Diffs elements in two lists.ndiff-list-dom: Diffs lists of DOMs using:dom/key.ndiff-list: Generates diff operations for lists (both keyed and unkeyed).ndiff-props-element: Diffs individual properties within a map.ndiff-props: Generates diff operations for property maps.ndom-ops-default: Default implementation fordom-ops.ndom-diff: The main function for computing the difference between two DOM trees.
4.5 std.dom.event (Event Handling)
This sub-namespace provides a standardized mechanism for handling UI events, including event propagation and dispatching to appropriate handlers.
Key Functions:
event-params: Converts event input into a standardized map.nevent-handler: Finds the most appropriate event handler by traversing the DOM hierarchy.nhandle-local: Handles events specifically for local components.n*handle-event: The main function for handling an event, dispatching it to the correct handler based on its ID and type.
4.6 std.dom.find (DOM Traversal and Querying)
This sub-namespace provides functions for searching and matching DOM nodes within a DOM tree.
Key Functions:
dom-match?: Checks if a DOM node's property matches a given value or predicate.ndom-find-props: Recursively searches for a DOM node within properties.ndom-find: Finds the first matching DOM node in a tree.ndom-find-all-props: Recursively finds all matching DOM nodes within properties.ndom-find-all: Finds all matching DOM nodes in a tree.
4.7 std.dom.impl (DOM Rendering and Manipulation)
This sub-namespace provides the core implementation for rendering, removing, and replacing DOM nodes, acting as the interface to the underlying UI toolkit.
Key Functions:
dom-render(multimethod): Renders a DOM node into an actual UI element.ndom-render-default: Default implementation fordom-render, which constructs the UI element usingitem-constructorand sets its properties usingitem-setters.ndom-init: Renders a DOM node if it hasn't been rendered yet.ndom-rendered: Renders a DOM form and returns the actual UI element.ndom-remove(multimethod): Removes a rendered UI element from the display.ndom-remove-default: Default implementation fordom-remove.ndom-replace(multimethod): Replaces one rendered UI element with another.n*dom-replace-default: Default implementation fordom-replace.
4.8 std.dom.invoke (DOM Invocation and Extension)
This sub-namespace provides a mechanism for extending the DOM system with new UI element types and components through std.protocol.invoke/-invoke-intern.
Key Functions:
invoke-intern-dom: A multimethod for defining new DOM element types (:value,:element) and components (:react,:local,:static).
4.9 std.dom.item (UI Element Abstraction)
This sub-namespace provides an abstraction layer for interacting with the actual UI elements (e.g., JavaFX nodes, HTML elements). It defines how to construct, set properties, get properties, and clean up these elements.
Key Functions:
item-constructor(multimethod): Returns the constructor function for a UI element based on its tag.nitem-setters(multimethod): Returns a map of setter functions for a UI element's properties.nitem-getters(multimethod): Returns a map of getter functions for a UI element's properties.nitem-access: Accesses a property of a UI element using its getter.nitem-create: Creates a new UI element.nitem-props-update(multimethod): Updates properties of a UI element based on diff operations.nitem-props-set(multimethod): Sets properties of a UI element.nitem-props-delete(multimethod): Deletes properties from a UI element.nitem-update: Applies a list of diff operations to a UI element.nitem-set-list(multimethod): Updates a list property of a UI element.nitem-cleanup(multimethod): Cleans up a UI element when it's removed.
4.10 std.dom.local (Local State Management)
This sub-namespace provides a mechanism for managing local, mutable state within UI components, allowing components to have their own internal state that can be updated reactively.
Core Concepts:
- Local State: Components can declare local state, which is managed by an atom.n* Watches and Triggers: Changes to local state can trigger watches and events.
Key Functions:
local-dom: Returns the nearest local component DOM in the hierarchy.nlocal-dom-state: Returns the state atom of the nearest local component.nlocal-parent,local-parent-state: Accessors for the parent local component and its state.ndom-ops-local: Generates diff operations for local component properties.nlocal-watch-create,local-watch-add,local-watch-remove: Functions for managing watches on local state.nlocal-trigger-add,local-trigger-remove: Functions for managing event triggers.nlocal-split-props: Splits properties into watchable and triggerable categories.nlocal-set: Sets local state properties and manages watches/triggers.ndom-send-local: Sends local events up the DOM hierarchy.ndom-apply-local: Applies diff operations to a local component.nlocalized-watch: Sets up initial watches and triggers for a local component.ndom-set-local: Sets a specific local state value.nlocalized-handler: Creates a handler for local component events.nlocalized-pre-render,localized-wrap-template,localized-pre-remove: Lifecycle hooks for local components.nlocalized: A mixin map for local components.n*local: Accesses local state within a component.
4.11 std.dom.mock (Mock UI Elements)
This sub-namespace provides mock implementations of UI elements for testing and development purposes, allowing DOM structures to be rendered and manipulated without a real UI toolkit.
Key Functions:
mock?: Checks if an object is a mock UI element.nmock-format: Formats a mock UI element for printing.nitem-props-delete-mock,item-props-set-mock,item-set-list-mock: Custom property manipulation functions for mock elements.
4.12 std.dom.react (Reactive State Management)
This sub-namespace provides a reactive state management system for UI components, allowing components to automatically re-render when their dependencies (atoms) change.
Core Concepts:
*react*: A dynamic var (volatile atom) that collects all atoms accessed within a reactive component's render function.n* Watches: Components automatically add watches to their dependent atoms, triggering re-renders on change.
Key Functions:
reactive-pre-render: Sets up the reactive context for a component.nreactive-wrap-template: Wraps a component's template function to track atom dependencies.nreactive-pre-remove: Cleans up reactive watches.nreactive: A mixin map for reactive components.nreact: Accesses a value from an atom, registering it as a dependency for the current reactive component.n*dom-set-state: Sets a state value in an atom, potentially triggering reactive updates.
4.13 std.dom.type (DOM Type System)
This sub-namespace defines the type system for DOM nodes, including metaclasses and metaprops, which describe the characteristics and behavior of different UI elements.
Core Concepts:
- Metaclass: A classification of UI elements (e.g.,
:dom/value,:dom/element,:dom/component).n* Metaprops: Metadata associated with a specific UI tag (e.g.,:mock/label), including its metaclass, metatype, constructor, and property definitions.
Key Functions:
+metaclass+,+metaprops-tag+: Atoms storing metaclass and metaprops definitions.nmetaclass,metaclass-remove,metaclass-add: Functions for managing metaclass definitions.nmetaprops,metaprops-add,metaprops-remove,metaprops-install: Functions for managing metaprops definitions.
4.14 std.dom.update (DOM Update and Patching)
This sub-namespace applies the diff operations generated by std.dom.diff to a rendered DOM tree, efficiently updating the UI.
Key Functions:
dom-apply(multimethod): Applies a list of diff operations to a DOM node.nupdate-set: Applies a:setoperation to properties.nupdate-list-insert,update-list-remove,update-list-update,update-list-append,update-list-drop: Functions for applying list-specific diff operations.nupdate-list: Applies list diff operations to a property.nupdate-props-delete,update-props-update: Functions for applying property-specific diff operations.nupdate-props: Applies diff operations to a property map.ndom-apply-default: Default implementation fordom-apply.ndom-update: Updates a DOM node to match a new DOM node by computing and applying diffs.ndom-refresh: Refreshes a DOM node, typically used for components.
4.15 Usage Pattern:
The std.dom module is essential for building dynamic and interactive user interfaces in Clojure. It provides:
- Declarative UI: Define UI as data, making it easier to reason about and manipulate.n Component-Based Architecture: Promote reusability and modularity in UI development.n Efficient Updates: Diffing and patching algorithms minimize UI re-renders.n Reactive Programming: Automatic UI updates in response to state changes.n Local State Management: Encapsulate component-specific state.n* Extensibility: A protocol-driven design allows for integration with various UI toolkits (e.g., JavaFX, HTML/JS).
By offering a comprehensive set of tools for UI definition, rendering, and management, std.dom empowers developers to create sophisticated user experiences within the foundation-base ecosystem.
5 std.html: A Comprehensive Summary
The std.html namespace provides a Clojure-idiomatic way to parse, manipulate, and generate HTML content, leveraging the powerful Jsoup Java library. It allows developers to represent HTML as Clojure data structures (trees), convert between these trees and Jsoup Node objects, and perform common HTML operations like parsing, formatting, and CSS-like selection. This module is particularly useful for web scraping, HTML templating, and processing HTML content within Clojure applications.
5.1 Core Concepts:
- Jsoup Integration: The module is built on top of Jsoup, providing access to its robust HTML parsing and manipulation capabilities.n HTML as Data: HTML structures are represented as Clojure vectors, where the first element is a keyword representing the tag, followed by an optional map of attributes, and then child elements (which can be strings, other vectors, or Jsoup
Nodeobjects).n Node Objects: JsoupNodeobjects (e.g.,Element,TextNode,Document) are used internally for efficient HTML manipulation.n* Conversion Functions: A set of functions for seamless conversion between HTML strings, JsoupNodeobjects, and Clojure tree representations.
5.2 Key Functions:
node->tree(multimethod):n Purpose: Converts a JsoupNodeobject (or its subclasses likeElement,TextNode,Document) into a Clojure tree representation.n Usage:(node->tree (parse "<body><div>hello</div>world</body>"))ntree->node:n Purpose: Converts a Clojure tree representation of HTML into a JsoupElementobject.n Usage:(tree->node [:body [:div "hello"] "world"])n* **parse**:n * **Purpose:** Parses an HTML string into a JsoupElementobject. It intelligently handles different HTML structures (full HTML, body fragments).n * **Usage:**(parse "helloworld")n* **inline**:n * **Purpose:** Removes all newlines from an HTML string, effectively inlining it.n * **Usage:**(inline (html [:body [:div "hello"] "world"]))ntighten:n Purpose: Removes unnecessary newlines and whitespace from HTML elements that contain no internal elements, making the HTML more compact.n Usage:(tighten "<b>\nhello\n</b>")ngenerate:n Purpose: Generates a formatted HTML string from a JsoupElementobject.n Usage:(generate (tree->node [:body [:div "hello"] "world"]))n* **html**:n * **Purpose:** A versatile function that converts various representations (string, vector tree, JsoupNode) into a formatted HTML string.n * **Usage:**(html [:body [:div "hello"] "world"])nhtml-inline:n Purpose: Generates an inlined HTML string (without newlines) from a representation.n Usage:(html-inline [:body [:div "hello"] "world"])n* **node**:n * **Purpose:** Converts various representations (string, vector tree) into a JsoupNodeobject.n * **Usage:**(node [:body [:div "hello"] "world"])ntree:n Purpose: Converts various representations (string, JsoupNode) into a Clojure tree representation of HTML.n Usage:(tree +content+)nITextProtocol:n Purpose: Defines atextmethod for extracting the text content from JsoupElementsorElementobjects.nselect:n Purpose: Applies a CSS selector query to a JsoupElementand returns matchingElements.n Usage:(select my-node "div.my-class")nselect-first:n Purpose: Applies a CSS selector query and returns the first matchingElement.n * Usage:(select-first my-node "p")
5.3 Usage Pattern:
This namespace is highly valuable for:
- Web Scraping: Easily parsing HTML from web pages and extracting specific data using CSS selectors.n HTML Templating: Generating dynamic HTML content from Clojure data.n Content Transformation: Modifying existing HTML structures programmatically.n Testing: Creating and asserting against HTML structures in tests.n Data Extraction: Extracting text or attributes from HTML documents.
By providing a seamless bridge between Clojure data and Jsoup's HTML manipulation capabilities, std.html empowers developers to work with HTML content effectively within their Clojure applications.
6 std.image: A Comprehensive Summary (including submodules)
The std.image module provides a comprehensive and extensible framework for image processing in Clojure. It abstracts away the complexities of underlying image representations (like Java's AWT BufferedImage) and offers a unified API for reading, writing, manipulating, and displaying images. The module emphasizes a "code-as-data" approach, allowing image properties and operations to be expressed as Clojure data structures.
6.1 std.image (Main Namespace)
This namespace serves as the primary entry point for image operations, aggregating and re-exporting key functionalities from its submodules. It defines core image concepts and provides high-level functions for common image tasks.
Core Concepts:
IRepresentationProtocol: The central abstraction for image data, defining methods for accessing image channels, size, model, and raw data, as well as creating subimages.nITransferProtocol: Defines methods for converting image data between different formats (e.g., byte-gray, int-argb) and writing images to sinks.nISizeProtocol: Defines methods for accessing image width and height.n* Default Settings: Dynamic vars (*default-type*,*default-model*,*default-view*) for configuring default image handling.
Key Functions:
default-type: Sets or retrieves the default image type (e.g.,BufferedImage).ndefault-model: Sets or retrieves the default image model (e.g.,:int-argb).ndefault-view: Sets or retrieves the default display view (e.g.,:awt).nimage?: Checks if an object is an image (implementsIRepresentation).nimage-channels: Returns the raw channel data of an image.nimage-size: Returns the size (width, height) of an image.nimage-model: Returns the color model of an image.nimage-data: Returns the raw pixel data of an image.nsize?: Checks if an object represents an image size.nheight,width: Returns the height or width of an image or size object.nsubimage: Extracts a rectangular subimage.nblank: Creates a blank image of a specified size and model.nread: Reads an image from a source (e.g., file path) into a specified model and type.nto-byte-gray: Converts an image to a byte-gray representation.nto-int-argb: Converts an image to an int-argb representation.nwrite: Writes an image to a sink (e.g., file path).nimage: Creates an image from size, model, and data.ncoerce: Converts an image to a different type or model.ndisplay-class: Shows which types can be displayed.n*display: Displays an image using a specified viewer.
6.2 std.image.awt (AWT Integration)
This sub-namespace provides the concrete implementation for handling images using Java's Abstract Window Toolkit (AWT) BufferedImage. It extends the std.image.protocol to BufferedImage and provides AWT-specific I/O and display functionalities.
Key Functions:
- Extends
BufferedImagetoIRepresentationandITransfer.nimage(multimethod): Creates aBufferedImagefrom image data.nblank(multimethod): Creates a blankBufferedImage.nread(multimethod): Reads an image into aBufferedImage.ndisplay(multimethod): Displays aBufferedImagein an AWT/Swing window.n*display-class(multimethod): Returns#{BufferedImage}.
6.3 std.image.awt.common (AWT Common Utilities)
This sub-namespace provides helper functions for working with AWT BufferedImage objects, including extracting size, model, and data, and performing conversions.
Key Functions:
type-lookup,name-lookup: Maps between AWTBufferedImagetypes andstd.imagemodel labels.nimage-size: Returns the size of aBufferedImage.nimage-model: Returns thestd.imagemodel of aBufferedImage.nimage-data: Returns the raw pixel data of aBufferedImage.nimage-channels: Returns the channel data of aBufferedImage.nsubimage: Extracts a subimage from aBufferedImage.nimage-to-byte-gray: Converts aBufferedImageto byte-gray data.nimage-to-int-argb: Converts aBufferedImageto int-argb data.nimage: Creates aBufferedImagefromstd.imagedata.
6.4 std.image.awt.display (AWT Image Display)
This sub-namespace provides functionality for displaying BufferedImage objects in a Swing JFrame.
Key Functions:
create-viewer: Creates a SwingJFrameandJComponentfor displaying images.n*display: Displays aBufferedImagein the created viewer, with options for channel selection.
6.5 std.image.awt.io (AWT Image I/O)
This sub-namespace provides functions for reading and writing BufferedImage objects using javax.imageio.ImageIO.
Key Functions:
providers: Lists availableImageIOservice providers (readers, writers, transcoders).nsupported-formats: Lists supported image formats (e.g., PNG, JPEG).nawt->int-argb: Converts an indexed or customBufferedImagetoTYPE_INT_ARGB.nread: Reads an image from an input source into aBufferedImage.nwrite: Writes aBufferedImageto an output sink in a specified format.
6.6 std.image.awt.rendering (AWT Rendering Hints)
This sub-namespace provides utilities for configuring rendering hints for Java2D Graphics2D objects, allowing control over image quality and performance.
Key Functions:
hint-lookup,hint-keys,hint-values: Maps between keyword representations of rendering hints and their AWTRenderingHintsconstants.nhint-options: Lists available options for rendering hints.nhints: Creates a map ofRenderingHintsobjects from keyword options.
6.7 std.image.base (Base Image Representation)
This sub-namespace defines a generic, data-oriented Image record that serves as a common representation for image data, independent of specific AWT BufferedImage implementations. It extends the std.image.protocol to this Image record.
Key Functions:
Imagerecord: A record that holdsmodel,size, anddatafor an image.nimage: Creates anImagerecord.nread(multimethod): Reads an image into anImagerecord.nblank(multimethod): Creates a blankImagerecord.ndisplay(multimethod): Displays anImagerecord.n*display-class(multimethod): Returns#{std.image.base.Image}.
6.8 std.image.base.common (Base Image Common Utilities)
This sub-namespace provides fundamental operations for manipulating the generic Image record, including channel creation, copying, subimaging, and conversions between different standard image types (color, grayscale).
Key Functions:
create-channels: Creates raw data arrays for image channels based on a model.nempty: Creates an emptyImagerecord.ncopy: Creates a copy of anImagerecord.nsubimage: Extracts a subimage from anImagerecord.ndisplay-standard-data: Converts raw image data (arrays) into Clojure vectors for display.nstandard-color-data->standard-gray: Converts standard color data to standard grayscale data.nstandard-color->standard-gray: Converts a standard color image to a standard grayscale image.nstandard-gray->standard-color: Converts a standard grayscale image to a standard color image.nstandard-type->standard-type: Converts between standard image types (color/gray).nmask-value: Extracts a value from an integer using a bitmask.nshift-value: Shifts a value by a specified number of bits.nretrieve-single: Retrieves a single channel's data from an image.nslice: Extracts a single channel (e.g., red, green, blue, alpha) from an image as a new grayscale image.nretrieve-all: Retrieves all channel data from an image.ncolor->standard-color: Converts a color image to a standard color image.ngray->standard-gray: Converts a grayscale image to a standard grayscale image.ntype->standard-type: Converts an image to a standard type (color or gray).nset-single-val: Calculates a single pixel value from channel inputs.nset-single: Sets a single channel's data.nset-all: Sets all channels' data according to a model.nconvert-base: Converts an image between different models via standard intermediate types.nconvert: Converts an image to a specified model.nbase-map: Returns the base map representation of an image.
6.9 std.image.base.display (Base Image Display)
This sub-namespace provides functions for rendering generic Image records as ASCII art strings, suitable for console output.
Key Functions:
render-string: Renders rows of pixel values into an ASCII string using a gradient table.nbyte-gray->rows: Converts byte-gray data into rows of pixel values.nrender-byte-gray: Renders a byte-gray image as an ASCII string.nint-argb->rows: Converts int-argb data into rows of grayscale pixel values.nrender-int-argb: Renders an int-argb image as an ASCII string.nrender: Renders an image (potentially slicing a channel) into an ASCII string.ndisplay: Prints an ASCII representation of an image to the console.n*animate: Animates a sequence of images in the console.
6.10 std.image.base.display.gradient (ASCII Gradient Generation)
This sub-namespace provides utilities for generating ASCII character gradients, used by std.image.base.display to render images as text.
Key Functions:
ramp-dark,ramp-light: Predefined strings of characters for dark and light gradients.ncreate-lookup: Creates a lookup map for characters based on a range.ncreate-single: Creates a single-character gradient map.ncreate-multi: Creates a multi-character gradient map (for wider pixels).nlookup-char: Looks up a character from a gradient table based on a numeric value.
6.11 std.image.base.model (Image Color Models)
This sub-namespace defines a comprehensive set of image color models, specifying how pixel data is organized and interpreted.
Core Concepts:
model-lookup: A map defining various image models (e.g.,:int-argb,:byte-gray,:3-byte-rgb), including their type (:color,:gray), metadata (channel types, spans), and data access definitions.n* Channel Access: Defines how to extract and combine individual color channels (alpha, red, green, blue) from raw pixel data.
Key Functions:
create-model: Creates an image model definition from a label.n*defaults*: Default color and grayscale models.nmodel-inv-table: Creates an inverse access table for setting data within an image.n*model: Creates an image model, allowing for overwrites of predefined models.
6.12 std.image.base.size (Image Size Utilities)
This sub-namespace provides utilities for working with image dimensions (width and height).
Key Functions:
- Extends
IPersistentVectorandIPersistentMaptoISize.nsize->map: Converts a size representation (vector or map) to a map with:widthand:height.nlength: Calculates the total number of pixels (width * height).
6.13 std.image.base.util (Base Image Low-Level Utilities)
This sub-namespace provides low-level utility functions for bit manipulation, array conversions, and generating code for packing/unpacking pixel data.
Key Functions:
type-lookup: Maps Java primitive types to their properties (size, array functions, unchecked functions, aset functions).nint->bytes,bytes->int: Converts between integers and byte arrays (for ARGB values).narray-fn: Returns the appropriate primitive array constructor function based on element size.nmask: Generates a bitmask.nform-params: Returns bitmasks and start positions for packing/unpacking values.n<<form,<<fn,<<: Functions for generating code and applying functions to pack multiple values into a single integer.n>>form,>>fn,>>: Functions for generating code and applying functions to unpack a single integer into multiple values.nbyte-argb->byte-gray,int-argb->byte-gray: Converts ARGB data to grayscale.nbyte-gray->int-argb: Converts grayscale data to ARGB.
6.14 std.image.protocol (Image Protocols)
This sub-namespace defines the core protocols that abstract image representation, manipulation, and display, allowing for extensible image handling.
Key Protocols:
ISize: Defines-widthand-height.nIRepresentation: Defines-channels,-size,-model,-data,-subimage.nITransfer: Defines-to-byte-gray,-to-int-argb,-write.nITransform: Defines-opfor image transformations.n Multimethods:-image,-blank,-read,-display,-display-class.
6.15 Usage Pattern:
The std.image module is essential for any Clojure application that needs to perform image processing tasks. It provides:
- Unified API: A consistent way to interact with images regardless of their underlying representation.n Extensibility: New image types and operations can be added by extending protocols.n Data-Oriented Approach: Image data and models are represented as Clojure data, facilitating manipulation.n Low-Level Control: Access to raw pixel data and bit manipulation utilities.n Debugging and Visualization: ASCII rendering for quick inspection of image content.
By offering a comprehensive and extensible image processing framework, std.image empowers developers to integrate image functionalities seamlessly into their Clojure applications.
7 std.json: A Comprehensive Summary
The std.json namespace provides a robust and flexible API for serializing and deserializing Clojure data to and from JSON format. It leverages the Jackson JSON processor, offering extensive customization options for handling various Clojure data types, including keywords, symbols, ratios, vars, and persistent collections. The module aims to provide a seamless and efficient way to work with JSON data in Clojure applications.
7.1 Core Concepts:
- Jackson Integration: Built on top of
com.fasterxml.jackson.databind.ObjectMapper, providing high-performance JSON processing.n Clojure Data Type Support: Custom serializers and deserializers are provided for common Clojure data structures and types, ensuring correct round-tripping between Clojure and JSON.n Customization: Offers various options for configuring theObjectMapper, such as pretty printing, handlingBigDecimals, escaping non-ASCII characters, and custom key encoding/decoding.n* Protocol-based I/O: Uses protocols (ReadValue,WriteValue) to abstract over different input/output sources (strings, files, streams).
7.2 Key Functions:
clojure-module:n Purpose: Creates acom.fasterxml.jackson.databind.module.SimpleModulethat registers custom serializers and deserializers for Clojure types.n Options: Supportsencode-key-fn,decode-key-fnfor custom key transformations,encodersfor additional custom serializers, anddate-format.nobject-mapper:n Purpose: Creates and configures acom.fasterxml.jackson.databind.ObjectMapperinstance with theclojure-moduleand other specified options.n Options:pretty(for pretty printing),bigdecimals,escape-non-ascii, andmodulesfor registering additional Jackson modules.n+default-mapper+: A defaultObjectMapperinstance with basic Clojure serialization.n+keyword-mapper+: AnObjectMapperthat deserializes JSON keys to Clojure keywords.n+keyword-case-mapper+: AnObjectMapperthat deserializes JSON keys to Clojure keywords, converting them to spear-case.n+keyword-js-mapper+: AnObjectMapperthat deserializes JSON keys, replacing underscores with hyphens and converting to keywords.n+keyword-spear-mapper+: AnObjectMapperthat deserializes JSON keys, replacing spaces with hyphens and converting to keywords.nReadValueProtocol:n Purpose: Defines the-read-valuemethod for reading JSON from various sources (File, URL, String, Reader, InputStream).nWriteValueProtocol:n Purpose: Defines the-write-valuemethod for writing JSON to various sinks (File, OutputStream, DataOutput, Writer).nread:n Purpose: Reads JSON content from an object (string, file, stream) and deserializes it into Clojure data.n Usage:(read "{\"a\":1,\"b\":2}")=>{"a" 1, "b" 2}nwrite:n Purpose: Serializes Clojure data into a JSON string.n Usage:(write {:a 1 :b 2})=>"{\"a\":1,\"b\":2}"nwrite-pp:n Purpose: Serializes Clojure data into a pretty-printed JSON string.n Usage:(write-pp {:a 1 :b 2})nwrite-bytes:n Purpose: Serializes Clojure data into a JSON byte array.n Usage:(String. (write-bytes {:a 1 :b 2}))nwrite-to:n Purpose: Writes Clojure data as JSON to a specified sink (file, output stream).n Usage:(write-to my-output-stream {:a 1 :b 2})nsys:resource-json:n * Purpose: Reads and caches JSON content from a classpath resource, deserializing keys to spear-case keywords.
7.3 Usage Pattern:
This namespace is crucial for any Clojure application that needs to:
- Interact with Web Services/APIs: Send and receive JSON data.n Store Configuration: Use JSON as a configuration file format.n Data Exchange: Exchange data with other systems that use JSON.n* Logging: Log structured data in JSON format.
By providing a powerful, customizable, and efficient JSON serialization/deserialization library, std.json simplifies working with JSON data in Clojure applications.
8 std.lib Recommendations
Here are some recommendations for new functionality in the broader std.lib codebase. These suggestions aim to fill in some common gaps in a foundational library and would make the foundation-base ecosystem more self-contained and powerful.
std.lib.json:n Justification: JSON is the de-facto standard for data interchange on the web. A dedicated namespace for JSON operations would be extremely valuable for any part of the system that needs to interact with web services or read/write configuration files.n Recommended Functionality:nencode: Serializes a Clojure data structure to a JSON string.ndecode: Parses a JSON string into a Clojure data structure.n Support for custom encoders/decoders for custom data types.n Functions for working with JSON schemas for validation.n Example Usage:n ```clojuren (require '[std.lib.json :as json])nn (def my-map {:a 1 :b "hello"})n (def json-string (json/encode my-map))n ;; => "{\"a\":1,\"b\":\"hello\"}"nn (json/decode json-string)n ;; => {:a 1, :b "hello"}n ```nnstd.lib.http:n Justification: Many modern applications need to communicate with other services over HTTP. A built-in HTTP client would simplify this greatly, providing a consistent API for making requests and handling responses.n Recommended Functionality:n Functions for all standard HTTP methods:get,post,put,delete,patch.n Easy ways to set headers, query parameters, and request bodies.n Automatic parsing of response bodies (e.g., JSON).n Support for both synchronous and asynchronous requests (leveragingstd.lib.future).n Connection pooling for performance.n Example Usage:n ```clojuren (require '[std.lib.http :as http])nn (def response (http/get "https://api.example.com/users/1"))n (:body response)n ;; => {:id 1, :name "John Doe"}n ```nnstd.lib.csv:n Justification: CSV is a common format for data import/export. A library for handling CSV files would be useful for data processing tasks.n Recommended Functionality:nread-csv: Reads a CSV file into a sequence of maps or vectors.nwrite-csv: Writes a sequence of maps or vectors to a CSV file.n Options for specifying delimiters, quote characters, and headers.n Example Usage:n ```clojuren (require '[std.lib.csv :as csv])nn (def data [{:name "John", :age 30} {:name "Jane", :age 25}])n (csv/write-csv "users.csv" data)nn (csv/read-csv "users.csv")n ;; => [{:name "John", :age "30"}, {:name "Jane", :age "25"}]n ```nnstd.lib.xml:n Justification: While less common than JSON, XML is still used in many enterprise systems and for configuration files. An XML parsing and generation library would be a valuable addition.n Recommended Functionality:nparse: Parses an XML string or file into a Clojure data structure (e.g., a nested map).nemit: Emits a Clojure data structure as an XML string.n Support for namespaces and attributes.n Example Usage:n ```clojuren (require '[std.lib.xml :as xml])nn (def xml-string " ")n (xml/parse xml-string)n ;; => {:tag :user, :content [{:tag :name, :content ["John"]}]}n ```nnJohn std.lib.crypto:n Justification:std.lib.securityprovides a good foundation, but a more comprehensive and higher-level cryptography library would be beneficial for applications with more advanced security requirements.n Recommended Functionality:n Symmetric encryption with common algorithms like AES-GCM.n Asymmetric encryption with RSA and EC.n Digital signatures with RSA and ECDSA.n Password hashing with algorithms like bcrypt or scrypt.n Key derivation functions.n Example Usage:n ```clojuren (require '[std.lib.crypto :as crypto])nn (def hashed-password (crypto/hash-password "my-secret-password"))n (crypto/verify-password "my-secret-password" hashed-password)n ;; => truen ```nnstd.lib.stats:n Justification: For applications that need to perform data analysis or monitoring, a basic statistics library would be very helpful.n Recommended Functionality:nmean,median,mode: For calculating measures of central tendency.nvariance,stdev: For calculating measures of dispersion.npercentiles,quartiles: For understanding the distribution of data.ncorrelation: For measuring the relationship between two variables.n Example Usage:n ```clojuren (require '[std.lib.stats :as stats])nn (def numbers [1 2 3 4 5])n (stats/mean numbers)n ;; => 3n (stats/stdev numbers)n ;; => 1.58...n ```nnstd.lib.date:n Justification:std.lib.timeis good for low-level time measurements, but a more feature-rich date and time library is needed for many applications.n Recommended Functionality:n Support for time zones.n Date and time arithmetic (e.g., adding/subtracting days, months, years).n Parsing and formatting dates and times in various formats (e.g., ISO 8601).n Functions for working with date ranges and intervals.n * Example Usage:n ```clojuren (require '[std.lib.date :as d])nn (def now (d/now))n (def tomorrow (d/plus now (d/days 1)))n (d/format tomorrow "yyyy-MM-dd")n ```
9 std.lib Summary
std.lib is the foundational utility library for the entire foundation-base ecosystem. It functions as a "prelude," aggregating and providing common functions used by all other modules. Its main purpose is to offer a consistent and extended set of core functionalities, tailored for the specific needs of the multi-language transpilation and runtime environment of the project.
Core Concepts:
- Aggregation:
std.libuses a custom helper,f/intern-all(fromstd.lib.foundation), to pull functions from its required sub-modules and make them available directly under thestd.libnamespace. This provides a single, convenient entry point for developers to access a wide range of utilities without needing torequirenumerous individual namespaces.nn Core Shadowing:std.libexplicitly excludes and shadows several core Clojure functions, such as->,->>,swap!,reset!,future, andmemoize. It provides its own enhanced implementations for these, often with added features like placeholder support in threading macros (->and->>) or more advanced caching strategies inmemoize.nn Sub-modules: The actual implementations of the functions are organized into a logical hierarchy of sub-modules. This modular design keeps the codebase clean and maintainable. The main sub-modules include:nstd.lib.atom: For atomic operations.nstd.lib.collection: For collection manipulations.nstd.lib.component: For the component lifecycle model.nstd.lib.deps: For dependency management.nstd.lib.env: For environment interactions.nstd.lib.foundation: For fundamental utilities.nstd.lib.function: For function-related helpers.nstd.lib.future: For asynchronous programming.nstd.lib.io: For input/output operations.nstd.lib.memoize: For memoization.nstd.lib.security: For cryptographic functions.nstd.lib.signal: For a signal/event system.nstd.lib.stream: For data streaming and transducers.nstd.lib.system: For managing system components.nstd.lib.time: For time-related utilities.nstd.lib.trace: For function tracing and debugging.nstd.lib.transform: For data transformation.nstd.lib.version: For version string parsing and comparison.nstd.lib.walk: For traversing nested data structures.nstd.lib.zip: For zipper-based navigation and manipulation of data structures.
Key Areas of Functionality (with Examples):
- Atom Manipulation (
std.lib.atom): Provides powerful functions for working with atoms, going beyond Clojure's core offerings.nswap-return!: Swaps the value of an atom and returns a vector of[old-value new-value].n ```clojuren (defonce my-atom (atom 0))n (swap-return! my-atom (fn [v] [v (inc v)]))n ;; => [0 1]n ```natom:get,atom:set: Functions for getting and setting values within nested maps inside an atom.n ```clojuren (defonce nested-atom (atom {:a {:b 1}}))n (atom:get nested-atom [:a :b])n ;; => 1n (atom:set nested-atom [:a :c] 2)n @nested-atomn ;; => {:a {:b 1, :c 2}}n ```nn Collections (std.lib.collection): A rich set of functions for working with Clojure's collections.nmap-keys,map-vals: For transforming map keys and values.n ```clojuren (map-keys #(keyword (clojure.string/upper-case (name %))) {:a 1 :b 2})n ;; => {:A 1, :B 2}n (map-vals inc {:a 1 :b 2})n ;; => {:a 2, :b 3}n ```nmerge-nested: For deep merging of nested maps.n ```clojuren (merge-nested {:a {:b 1}} {:a {:c 2}})n ;; => {:a {:b 1, :c 2}}n ```ntree-flatten,tree-nestify: For converting between flat and nested map structures.n ```clojuren (tree-flatten {:a {:b {:c 1}}})n ;; => {:a/b/c 1}n (tree-nestify {:a/b/c 1})n ;; => {:a {:b {:c 1}}}n ```nn Concurrency (std.lib.future): A customCompletableFuture-basedfutureimplementation.nfuture,then,catch: For creating and chaining asynchronous operations.n ```clojuren (-> (future (Thread/sleep 100) (+ 1 2))n (then [result] ( result 2))n (then [result] (println "Final result:" result)))n ;; Prints "Final result: 6" after a delay.n ```nn Dependency Management (std.lib.deps): A system for managing dependencies between components.ndeps-ordered: For resolving and ordering dependencies in a dependency graph.n ```clojuren (deps-ordered (context {:a #{:b} :b #{:c} :c #{}}))n ;; => '(:c :b :a)n ```nn Environment (std.lib.env): Functions for interacting with the development and runtime environment.nprn,pp,pl: Enhanced printing functions that include namespace and line number information.n ```clojuren (pl {:a 1 :b 2})n ;; Prints the map with line numbers and file info.n ```nmeter: For measuring the execution time of code blocks.n ```clojuren (meter "My expensive operation" (Thread/sleep 100))n ;; Prints the time taken for the operation.n ```nn System Components (std.lib.system): A hierarchical component model for building applications.nsystem: For defining a system of interconnected components.n ```clojuren (def topology {:db [MyDatabase] :web [WebServer :db]})n (def my-system (system topology {:db {:port 5432} :web {:port 8080}}))n (start my-system)n ```nn Zippers (std.lib.zip): A powerful zipper implementation for navigating and manipulating tree-like data structures.nvector-zip: For creating a zipper from a vector.n ```clojuren (-> (vector-zip [1 [2 3] 4])n (zip/step-inside)n (zip/step-right)n (zip/step-inside)n (zip/replace-right 99)n (zip/root-element))n ;; => [1 [2 99] 4]n ```
10 std.log: A Comprehensive Summary (including submodules)
The std.log module provides a flexible and extensible logging framework for Clojure applications, designed to handle various logging scenarios from simple console output to complex profiling and tracing. It offers a protocol-based approach, allowing for different logger implementations, and includes features like structured logging, context management, and advanced formatting for console output.
10.1 std.log (Main Namespace)
This namespace serves as the primary entry point for the logging system, aggregating and re-exporting key functionalities from its submodules. It provides high-level macros and functions for logging messages at different levels, managing logger instances, and controlling logging behavior.
Key Re-exported Functions:
- From
std.log.common:put-logger!,set-logger!,set-static!,set-level!,set-context!.n Fromstd.log.console:console-logger.n Fromstd.log.core:identity-logger,multi-logger,basic-logger,step.n Fromstd.log.form:log-meta,log-runtime,log-context,log,verbose,debug,info,warn,error,fatal.n Fromstd.log.profile:spy,show,trace,track,status,silent,action,meter,block,section,profile,note,task,todo.
Key Functions:
create: Creates a component-compatible logger.nlogger: Creates and starts a logger.nlogger?: Checks if an object is a logger.nwith-indent(macro): Executes body with a given indent.nwith-level(macro): Executes body with a given log level.nwith-logger(macro): Executes code with a specified logger.nwith-overwrite(macro): Executes code with a given overwrite context.ncurrent-context: Returns the current logging context.nwith-context(macro): Executes code with a given context.nwith(macro): Enables targeted printing of statements.nwith-logger-basic(macro): Executes code with the basic logger.n*with-logger-verbose(macro): Executes code with a verbose logger.
10.2 std.log.common (Common Logging Utilities)
This sub-namespace provides shared helper functions and dynamic variables for managing logging levels, contexts, and logger instances.
Core Concepts:
- Dynamic Variables:
*level*,*overwrite*,*context*,*trace*,*static*,*logger*,*logger-basic*,*logger-verbose*.n* Log Levels:+levels+maps keywords (e.g.,:debug,:info) to numeric priorities.
Key Functions:
set-static!,set-level!,set-context!,set-logger!,put-logger!: Functions for setting and updating global logging parameters.ndefault-logger: Returns the default logger instance.nbasic-logger: Returns a basic logger instance.n*verbose-logger: Returns a verbose logger instance.
10.3 std.log.console (Console Logger)
This sub-namespace implements a console logger that formats and prints log entries to the console, with extensive styling and customization options.
Core Concepts:
+style+: A map defining default styling for different parts of a log entry (header, body, meter, status).n+levels+: Defines color schemes for different log levels.nConsoleLoggerRecord: The concrete implementation of a console logger.
Key Functions:
style-default: Retrieves default styling.njoin-with: Joins strings with a separator.nconsole-pprint: Pretty-prints data for console output.nconsole-format-line: Formats a single line for console output.nconsole-display?: Checks if an item should be displayed.nconsole-render: Renders a log entry based on its style.nconsole-header-label,console-header-position,console-header-date,console-header-message,console-header: Functions for rendering the log header.nconsole-meter-trace,console-meter-form,console-meter: Functions for rendering meter-related information.nconsole-status-outcome,console-status-duration,console-status-start,console-status-end,console-status-props,console-status: Functions for rendering status information.nconsole-body-console-text,console-body-console: Functions for rendering console text in the body.nconsole-body-data-context,console-body-data: Functions for rendering data in the body.nconsole-body-exception,console-body: Functions for rendering exceptions in the body.nconsole-format: Formats the entire log entry for console output.nlogger-process-console: Processes log entries for console output.nconsole-write: Writes a log entry to the console.n*console-logger: Creates a console logger instance.
10.4 std.log.core (Core Logger Implementations)
This sub-namespace provides core logger implementations, including an identity logger (which simply returns the log entry), a multi-logger (which dispatches to multiple loggers), and a basic logger (which prints to *out*). It also defines helper functions for processing log entries and exceptions.
Core Concepts:
ILoggerProtocol: Defines the-logger-writemethod for writing log entries.nIdentityLoggerRecord: A logger that returns the log entry unchanged.nMultiLoggerRecord: A logger that dispatches log entries to multiple child loggers.n*BasicLoggerRecord: A logger that prints log entries to*out*.
Key Functions:
logger-submit: Submits a log entry to a logger's queue.nlogger-process: Processes a log entry, applying anyfn/processtransformations.nlogger-enqueue: Enqueues a log entry for processing.nprocess-exception: Converts aThrowableinto a map for logging.nlogger-message: Constructs a standardized log message map.nlogger-start,logger-info,logger-stop: Lifecycle and info functions for loggers.nlogger-init: Initializes logger settings.nidentity-logger: Creates an identity logger.nmulti-logger: Creates a multi-logger.nlog-raw: Sends raw data to the logger.nbasic-write: Writes a log entry to*out*.nbasic-logger: Creates a basic logger.nstep(macro): Logs a step in a process.
10.5 std.log.element (Log Element Formatting)
This sub-namespace provides helper functions for formatting individual elements of a log entry, such as ANSI styling, headings, and time/duration displays.
Key Functions:
style-ansi: Constructs ANSI style codes from a style map.nstyle-heading: Formats a heading with styling.nelem-daily-instant: Formats a label and instant (date/time).nelem-ns-duration: Formats a label and nanosecond duration.nelem-position: Formats a code position (namespace, function, line, column).
10.6 std.log.form (Log Form Macros)
This sub-namespace provides macros for generating log entries from Clojure forms, capturing metadata like line numbers and function names. It also defines macros for different log levels.
Key Functions:
log-meta: Captures metadata from a form.nlog-function-name: Extracts a function name from a mangled string.nlog-runtime-raw,log-runtime: Captures runtime information (function, method, filename).nlog-check: Checks if a log entry should be processed based on its level.nto-context: Converts various inputs to a log context map.nlog-fn: The core function for logging an entry.nlog-form: Generates a log entry from a form.nwith-context(macro): Applies a context to the current one.nlog-context: Creates a log context form.nlog(macro): The main macro for logging messages.nlog-data-form,deflog-data(macro): Macros for logging data at different levels (verbose, debug, info, warn).n*log-error-form,deflog-error(macro): Macros for logging errors (error, fatal).
10.7 std.log.match (Log Entry Matching)
This sub-namespace provides functions for filtering log entries based on various criteria, such as log level, namespace, function name, and custom filters.
Key Functions:
filter-base: Matches a value against a filter (regex, string, function).nfilter-include: Checks if a value matches any of the include filters.nfilter-exclude: Checks if a value does not match any of the exclude filters.nfilter-value: Filters a value based on include, exclude, and ignore criteria.nmatch-filter: Matches an entry against a filter map.n*match: The main function for matching a log entry against logger settings.
10.8 std.log.profile (Profiling and Tracing)
This sub-namespace provides macros for profiling code execution, tracing function calls, and displaying various metrics. It integrates with the logging system to output structured performance data.
Core Concepts:
- Spy: Logs the start and end of a function's execution, including its duration.n Trace: Tracks function calls within a nested execution flow.n Meter: Measures the execution time of a block of code.n* Status: Logs the outcome of an operation.
Key Functions:
spy-fn: Constructs a spy function.nbind-trace: Binds a trace ID to the log context.nspy-form: Helper for thespymacro.ndefspy(macro): Creates a spy macro.non-grey,on-white,on-color: Functions for generating console styles.nitem-style: Styles a log entry.nnote,spy,track,status,show,todo,action(macros): Specific profiling and tracing macros.nmeter-fn: Constructs a meter function.nmeter-form: Helper for themetermacro.ndefmeter(macro): Creates a meter macro.nsilent,trace,profile,meter,block,section,task(macros): Specific profiling and tracing macros.
10.9 std.log.template (Log Message Templating)
This sub-namespace provides a simple templating system for log messages, allowing messages to be rendered using Mustache-like syntax.
Key Functions:
add-template,remove-template,has-template?,list-templates: Manages message templates.n*render-message: Renders a log message using a template.
10.10 Usage Pattern:
The std.log module is essential for:
- Debugging: Providing detailed information about program execution.n Monitoring: Tracking application behavior and performance.n Auditing: Recording important events and actions.n Profiling: Identifying performance bottlenecks.n Structured Logging: Outputting log data in a machine-readable format.
By offering a comprehensive and customizable logging solution, std.log empowers developers to gain deeper insights into their applications and build more robust and maintainable software.
11 std.make: A Comprehensive Summary (including submodules)
The std.make module provides a comprehensive framework for automating build processes, managing project configurations, and interacting with version control systems (specifically Git and GitHub). It aims to simplify the creation and maintenance of Makefiles, manage project dependencies, and streamline common development workflows like building, testing, and releasing software. The module is designed to be extensible, allowing for custom build steps and integration with various tools.
11.1 std.make (Main Namespace)
This namespace serves as the primary entry point for the build automation system, aggregating and re-exporting key functionalities from its submodules. It provides high-level functions and macros for common build tasks.
Key Re-exported Functions:
- From
std.make.compile:with:mock-compile,types:add,types:list,types:remove,build.n Fromstd.make.common:with:internal-shell,triggers-clear,triggers-get,triggers-list,triggers-purge,triggers-set,get-triggered,make-config,dir,dir:exists?,dir:teardown,run:shell,run,run-close,run-internal,run:init,run:package,run:dev,run:test,run:release,run:start,run:stop.n Fromstd.make.github:dir:repo-rebuild,dir:repo-setup,gh:token,gh:user,gh:exists?,gh:commit,gh:push,gh:save,gh:clone,gh:setup,gh:setup-init,gh:setup-remote,gh:local-purge,gh:dwim-init,gh:dwim-push,with-verbose.n Fromstd.make.project:def.make,build-all,build-at,build-default,build-triggered,is-changed?.n Fromstd.make.readme:org:tangle,org:readme.n* Fromstd.make.bulk:bulk-container-build,bulk-container-filter,bulk-build,bulk,bulk-gh-init,bulk-gh-push.
11.2 std.make.bulk (Bulk Operations)
This sub-namespace provides functions for performing bulk operations across multiple projects or configurations, such as building multiple containers or pushing changes to multiple GitHub repositories.
Key Functions:
make-bulk-get-keys: Determines the order of projects to build based on dependencies and changes.nmake-bulk-build: Builds multiple projects in bulk.nmake-bulk: Orchestrates a bulk build process, including logging and timing.nmake-bulk-container-filter: Filters configurations based on container names.nmake-bulk-container-build: Builds multiple containers in bulk.nmake-bulk-gh-init: Initializes multiple GitHub repositories in bulk.nmake-bulk-gh-push: Pushes changes to multiple GitHub repositories in bulk.
11.3 std.make.common (Common Makefile Utilities)
This sub-namespace provides shared helper functions and dynamic variables for managing Makefile configurations, running shell commands, and handling triggers.
Core Concepts:
*triggers*: An atom storing a map of configurations to their associated triggers.n*tmux*: A dynamic var to control whethertmuxis used for running commands.n*internal-shell*: A dynamic var to control whether commands are run in an internal shell.n*MakeConfigRecord: Represents aMakefileconfiguration.
Key Functions:
with:triggers(macro): Binds the*triggers*atom.ntriggers-purge,triggers-set,triggers-clear,triggers-get,triggers-list: Functions for managing triggers.nget-triggered: Retrieves configurations based on a trigger namespace.nwith:internal-shell(macro): Binds*internal-shell*.nmake-config-string: Returns a string representation of aMakeConfig.nmake-config?: Checks if an object is aMakeConfig.nget-config-tag: Retrieves the tag of aMakeConfig.nmake-config-defaults: Returns defaultMakeConfigsettings.nmake-config-map: Creates aMakeConfigmap.nmake-config: Creates aMakeConfiginstance.nmake-config-update: Updates aMakeConfig.nmake-dir: Returns the build directory for aMakeConfig.nmake-run: Runs amakecommand.nmake-run-close: Closes atmuxwindow.nmake-run-internal: Runsmakecommands internally.nmake-shell: Opens a terminal in the build directory.nmake-run-init,make-run-package,make-run-release,make-run-dev,make-run-test,make-run-start,make-run-stop: Specificmakecommands.nmake-dir-setup: Sets up the build directory.nmake-dir-exists?: Checks if the build directory exists.n*make-dir-teardown: Deletes the build directory.
11.4 std.make.compile (Compilation Utilities)
This sub-namespace provides utilities for compiling various types of files and resources, including custom formats, directories, and language-specific modules.
Core Concepts:
*mock-compile*: A dynamic var to enable mock compilation for testing.n* Compilation Types: Supports:resource,:directory,:custom,:script,:module.graph,:module.single,:module.schema.
Key Functions:
with:mock-compile(macro): Enables mock compilation.ncompile-fullbody: Combines header, body, and footer into a full body.ncompile-out-path: Generates the output path for a compiled file.ncompile-write: Writes compiled content to a file.ncompile-summarise: Summarizes compilation results.ncompile-resource: Copies resources to the build directory.ncompile-directory: Copies a directory to the build directory.ncompile-custom: Compiles custom content.ntypes-list,types-add,types-remove: Manages compilation types.ncompile-ext-fn(multimethod): Extensible function for compiling different file extensions (e.g.,:blank,:raw,:edn,:json,:yaml,:toml,:html,:css,:sql,:redis,:vega,:gnuplot,:graphviz,:gitignore,:nginx.conf,:dockerfile,:readme.md,:makefile,:package.json).ncompile-resolve: Resolves a symbol or pointer.ncompile-ext: Compiles files of different extensions.ncompile-single: Compiles a single file.ncompile-section: Compiles a section of aMakefile.ncompile-directive: Compiles a directive within aMakefile.n*compile: The main function for compiling files based on aMakeConfig.
11.5 std.make.github (GitHub Integration)
This sub-namespace provides functions for interacting with GitHub repositories, including committing, pushing, cloning, and setting up remote repositories.
Core Concepts:
*verbose*: A dynamic var to control verbose output for Git commands.
Key Functions:
with-verbose(macro): Controls verbose output.ngh-sh-opts: Creates standard shell options for Git commands.ngh-commit: Creates a Git commit.ngh-push: Pushes changes to GitHub.ngh-save: Commits and pushes changes.ngh-user,gh-token: Retrieves GitHub user and token from environment variables.ngh-exists?: Checks if a GitHub repository exists.ngh-setup-remote: Creates a remote GitHub repository.ngh-setup-local-init: Initializes a local Git repository and links it to a remote.ngh-setup-local-clone: Clones a GitHub repository.ngh-clone: Forces a Git clone.ngh-setup: Sets up a GitHub repository (clones or initializes).ngh-local-purge: Purges all checked-in files from a Git repository.ngh-refresh: Regenerates a Git repository.ngh-dwim-init: Initializes a project and pushes it to GitHub.n*gh-dwim-push: Pushes changes to GitHub.
11.6 std.make.makefile (Makefile Generation)
This sub-namespace provides functions for generating Makefile content from Clojure data structures.
Key Functions:
emit-headers: EmitsMakefileheaders (variables).nemit-target: Emits aMakefiletarget with its dependencies and commands.nwrite: Writes aMakefilefrom a Clojure data structure.
11.7 std.make.project (Project Management)
This sub-namespace provides functions for managing project configurations, building projects, and tracking changes.
Core Concepts:
def.makeMacro: Defines aMakefileconfiguration.
Key Functions:
makefile-parse: Parses aMakefilefor its sections.nbuild-default: Builds the default section of aMakefile.nchanged-files: Retrieves a list of changed files from a build result.nis-changed?: Checks if a project has changed.nbuild-all: Builds all sections of aMakefile.nbuild-at: Builds a specific section of aMakefile.ndef-make-fn: Implementation fordef.make.n*build-triggered: Builds projects based on triggered namespaces.
11.8 std.make.readme (README Generation)
This sub-namespace provides functions for generating README.md files from Org-mode files, including tangling code blocks.
Key Functions:
has-orgfile?: Checks if an Org-mode file exists.ntangle-params: Extracts tangle parameters from an Org-mode file.ntangle-parse: Parses an Org-mode file for tangle blocks.ntangle: Extracts code blocks from an Org-mode file and writes them to separate files.nmake-readme-raw: Filters out build-related sections from a README.n*make-readme: Generates aREADME.mdfile from an Org-mode file.
11.9 Usage Pattern:
The std.make module is essential for automating various aspects of software development within the foundation-base project. It provides:
- Unified Build System: A consistent way to define and execute build steps across different projects and languages.n Project Scaffolding: Tools for setting up new projects with predefined structures and configurations.n Version Control Integration: Streamlined workflows for committing, pushing, and managing GitHub repositories.n Documentation Generation: Automated creation of
README.mdfiles from Org-mode sources.n Extensibility: A modular design that allows for custom build steps and integrations.
By offering a comprehensive set of build automation and project management tools, std.make simplifies the development lifecycle and promotes consistency across the foundation-base ecosystem.
12 std.math: A Comprehensive Summary (including submodules)
The std.math module provides a collection of mathematical functions and utilities for Clojure, covering basic arithmetic, statistical calculations, random number generation, and Markov chain analysis. It aims to offer a convenient and comprehensive set of tools for numerical and probabilistic computations.
12.1 std.math (Main Namespace)
This namespace serves as the primary entry point for mathematical operations, aggregating and re-exporting key functionalities from its submodules.
Key Re-exported Functions:
- From
std.math.common:abs,ceil,factorial,floor,combinatorial,log,loge,log10,mean,median,mode,variance,stdev,skew,kurtosis,histogram.n Fromstd.math.aggregate:aggregates.n Fromstd.math.random:rand-seed!,rand,rand-int,rand-nth,rand-digits,rand-sample.
12.2 std.math.aggregate (Aggregation Functions)
This sub-namespace provides functions for calculating various aggregate statistics on collections of numbers.
Key Functions:
max-fn: Returns the maximum value in a collection.nmin-fn: Returns the minimum value in a collection.nrange-fn: Returns the range (max - min) of a collection.nmiddle-fn: Returns the middle element of a sorted collection.nwrap-not-nil: A helper to wrap functions that should ignorenilvalues.n+aggregations+: A map of common aggregation functions (first, last, middle, mean, sum, max, min, range, stdev, mode, median, skew, variance, random).naggregates: Calculates a set of aggregate statistics for a collection.
12.3 std.math.common (Common Mathematical Functions)
This sub-namespace provides a collection of fundamental mathematical and statistical functions.
Key Functions:
abs: Absolute value.nsquare: Squares a number.nsqrt: Square root.nceil: Ceiling of a number.nfloor: Floor of a number.nfactorial: Factorial of a number.ncombinatorial: Binomial coefficient (n choose i).nlog: Logarithm to an arbitrary base.nloge: Natural logarithm.nlog10: Base-10 logarithm.nmean: Arithmetic mean.nmode: Mode (most frequent value).nmedian: Median (middle value).npercentile: Calculates a percentile.nquantile: Splits data into quantiles.nvariance: Sample variance.nstdev: Standard deviation.nskew: Skewness.nkurtosis: Kurtosis.n*histogram: Creates a histogram.
12.4 std.math.markov (Markov Chain Analysis)
This sub-namespace provides functions for working with Markov chains, including calculating cumulative probabilities and generating sequences based on a probability matrix.
Key Functions:
cumulative: Reassembles probabilities in cumulative order.nselect: Selects an item randomly based on probabilities.ngenerate: Generates an infinite stream of tokens from a probability matrix.ntally: Helper forcollate.ncollate: Generates a probability map from a sequence of tokens.
12.5 std.math.random (Random Number Generation)
This sub-namespace provides functions for generating various types of random numbers and samples, leveraging org.apache.commons.math3.random.MersenneTwister.
Key Functions:
rand-gen: Creates a random number generator.nrand-seed!: Sets the seed of a random number generator.nrand: Generates a random double between 0 and 1.nrand-int: Generates a random integer less thann.nrand-nth: Returns a random element from a collection.nrand-normal: Generates a random number from a normal distribution.nrand-digits: Generates a random n-digit string.n*rand-sample: Samples from a collection with specified proportions.
12.6 Usage Pattern:
The std.math module is useful for:
- Statistical Analysis: Performing common statistical calculations on data.n Data Generation: Generating random numbers and sequences.n Modeling: Implementing probabilistic models like Markov chains.n* Numerical Computations: Basic mathematical operations.
By providing a diverse set of mathematical tools, std.math supports various analytical and computational tasks within Clojure applications.
13 std.object: A Comprehensive Summary (including submodules)
The std.object module provides a powerful and extensible framework for introspecting, manipulating, and extending Java objects in Clojure. It offers a unified API for querying class metadata, accessing fields and methods, and defining custom behaviors for various object types. This module is crucial for bridging the gap between Clojure's dynamic nature and Java's static type system, enabling seamless interoperability and advanced metaprogramming capabilities.
13.1 std.object (Main Namespace)
This namespace serves as the primary entry point for object manipulation, aggregating and re-exporting key functionalities from its submodules. It provides high-level functions for common object-oriented tasks.
Key Re-exported Functions:
- From
std.object.element.class:class-convert.n Fromstd.object.element.common:element?,element,context-class.n Fromstd.object.element:to-element,class-info,class-hierarchy,constructor?,method?,field?,static?,instance?,public?,private?,plain?.n Fromstd.object.query:query-class,query-instance,query-hierarchy,delegate.n Fromstd.object.framework.access:get,get-in,set,keys,meta-clear.n Fromstd.object.framework.read:meta-read,meta-read-exact,meta-read-exact?,to-data,to-map,read-ex,read-getters-form,read-getters,read-all-getters,read-fields.n Fromstd.object.framework.struct:struct-fields,struct-getters,struct-accessor.n Fromstd.object.framework.write:meta-write,meta-write-exact,meta-write-exact?,from-data,write-ex,write-setters-form,write-setters,write-all-setters,write-fields.n Fromstd.object.framework:vector-like,map-like,string-like,unextend.
13.2 std.object.element (Object Element Abstraction)
This sub-namespace provides an abstraction layer for representing Java reflection objects (methods, fields, constructors) as Clojure data structures (Element records). This allows for a unified way to query and manipulate these elements.
Core Concepts:
ElementRecord: A data structure representing a Java reflection object, containing itsname,tag(method, field, constructor),modifiers,type,containerclass, anddelegate(the raw Java reflection object).
Key Functions:
to-element: Converts ajava.lang.reflectobject to anElement.nelement-params: Returns the parameter types of anElement.nclass-info: Retrieves information about a class.nclass-hierarchy: Retrieves the class and interface hierarchy.nconstructor?,method?,field?: Predicates for element types.n*static?,instance?,public?,private?,protected?,plain?: Predicates for element modifiers.
13.3 std.object.element.class (Class Conversion Utilities)
This sub-namespace provides utilities for converting between different representations of Java classes and types (e.g., Class objects, symbols, strings, raw type signatures).
Key Functions:
type->raw: Converts aClassor symbol to its raw type signature string.nraw-array->string: Converts a raw array type signature to a human-readable string.nraw->string: Converts a raw type signature to a human-readable string.nstring-array->raw: Converts a human-readable array type string to a raw type signature.nstring->raw: Converts any string to its raw type signature.n*class-convert(multimethod): Converts a class or type representation to another (e.g.,:class,:container,:symbol,:raw,:string).
13.4 std.object.element.common (Common Element Utilities)
This sub-namespace provides common helper functions for working with Element records, such as determining the context class and checking assignability.
Key Functions:
context-class: Returns theClassobject for a given object or class.nassignable?: Checks if a sequence of classes is assignable to another sequence.n-invoke-element(multimethod): Base method for extendinginvokeforElementtypes.n-to-element(multimethod): Base method for extendingto-elementfrom Java reflection objects.n-element-params(multimethod): Base method for extending parameter retrieval forElementtypes.n-format-element(multimethod): Base method for extendingtoStringforElementtypes.nelement: Creates anElementrecord.n*element?: Checks if an object is anElement.
13.5 std.object.element.impl.constructor (Constructor Element Implementation)
This sub-namespace provides the implementation details for Element records representing Java constructors.
Key Functions:
- Extends
common/-invoke-elementandcommon/-to-elementforjava.lang.reflect.Constructor.
13.6 std.object.element.impl.field (Field Element Implementation)
This sub-namespace provides the implementation details for Element records representing Java fields.
Key Functions:
patch-field: Makes aFieldaccessible.narg-params: Returns argument parameters for field getters/setters.nthrow-arg-exception: Throws an argument exception.ninvoke-static-field: Invokes a static field.ninvoke-instance-field: Invokes an instance field.n* Extendscommon/-invoke-elementandcommon/-to-elementforjava.lang.reflect.Field.
13.7 std.object.element.impl.hierarchy (Class Hierarchy Utilities)
This sub-namespace provides utilities for traversing and analyzing class hierarchies, particularly for finding method origins.
Key Functions:
has-method: Checks if a method exists in a class.nmethods-with-same-name-and-count: Finds methods with the same name and parameter count.nhas-overridden-method: Checks if a method is overridden.n*origins: Lists all classes that contain a particular method.
13.8 std.object.element.impl.method (Method Element Implementation)
This sub-namespace provides the implementation details for Element records representing Java methods.
Key Functions:
invoke-static-method: Invokes a static method.ninvoke-instance-method: Invokes an instance method.n Extendscommon/-invoke-elementandcommon/-to-elementforjava.lang.reflect.Method.
13.9 std.object.element.impl.multi (Multi-Element Handling)
This sub-namespace handles the combination of multiple Element records (e.g., overloaded methods) into a single multi-element.
Key Functions:
get-name: Retrieves the common name of multiple elements.nto-element-array: Converts a nested map of elements to a flat sequence.nmulti-element: Combines multiple elements into one.nto-element-map-path: Creates a map path for an element.nelegible-candidates: Finds eligible candidates based on argument list.nfind-method-candidate: Finds the best method candidate.nfind-field-candidate: Finds the best field candidate.nfind-candidate: Finds the best element candidate (method or field).n Extendscommon/-invoke-elementfor multi-elements.
13.10 std.object.element.impl.type (Element Type Utilities)
This sub-namespace provides low-level utilities for working with Java reflection types, including setting accessible flags and extracting modifiers.
Key Functions:
set-accessible: Sets the accessible flag for a reflection object.nadd-annotations: Adds annotations to an element.nseed: Returns preliminary attributes for creating an element.
13.11 std.object.element.modifier (Modifier Utilities)
This sub-namespace provides utilities for converting between integer representations of Java modifiers and human-readable sets of keywords.
Key Functions:
flags,field-flags,method-flags: Maps of modifier flags.nint-to-modifiers: Converts an integer to a set of modifier keywords.nmodifiers-to-int: Converts a set of modifier keywords to an integer.
13.12 std.object.element.util (Element Utility Functions)
This sub-namespace provides general utility functions for working with Element records, such as boxing arguments and matching parameter types.
Key Functions:
box-arg: Converts a value to a primitive type if necessary.nset-field: Sets the value of a field.nparam-arg-match: Checks if an argument type matches a parameter type.nparam-float-match: Matches float parameters to integer arguments.nis-congruent: Checks if argument types are congruent with parameter types.nthrow-arg-exception: Throws an argument exception.nbox-args: Boxes arguments to match parameter types.nformat-element-method: Formats a method element.nelement-params-method: Returns method parameters.
13.13 std.object.framework (Object Framework)
This sub-namespace provides a framework for extending Clojure's object model to seamlessly interact with Java objects, allowing them to behave like Clojure maps, vectors, or strings.
Key Functions:
string-like(macro): Extends a class to behave like a string.nmap-like(macro): Extends a class to behave like a map.nvector-like(macro): Extends a class to behave like a vector.nunextend: Removes framework extensions for a class.ninvoke-intern-object: Creates an invoke form for an object.
13.14 std.object.framework.access (Object Accessors)
This sub-namespace provides functions for accessing and modifying object properties using keywords or paths, abstracting away direct Java reflection.
Key Functions:
meta-clear: Clears all meta-read and meta-write definitions for a class.nget-with-keyword,get-with-array: Retrieves properties using keywords or arrays.nget: Retrieves a property.nget-in: Retrieves a nested property.nkeys: Retrieves all accessible property keys.nset-with-keyword: Sets a property using a keyword.nset: Sets properties using a map or key-value pair.
13.15 std.object.framework.map-like (Map-Like Extension)
This sub-namespace provides the implementation for extending Java classes to behave like Clojure maps, allowing for property access and manipulation using map-like syntax.
Key Functions:
key-selection: Selects map entries based on include/exclude keys.nread-proxy-functions: Creates proxy functions for reading properties.nwrite-proxy-functions: Creates proxy functions for writing properties.nextend-map-read: Extends a class with map-like read capabilities.nextend-map-write: Extends a class with map-like write capabilities.n*extend-map-like(macro): Extends a class to behave like a map.
13.16 std.object.framework.print (Print Extension)
This sub-namespace provides utilities for extending the print-method for Java classes, allowing for custom string representations.
Key Functions:
assoc-print-vars: Associates print-related variables.nformat-value: Formats an object into a readable string.nextend-print(macro): Extends theprint-methodfor a class.
13.17 std.object.framework.read (Object Reading)
This sub-namespace provides functions for reading object properties, including metadata, fields, and getter methods, and converting objects to Clojure data structures.
Key Functions:
meta-read,meta-read-exact,meta-read-exact?: Accesses and checks read metadata.nread-fields,read-all-fields: Reads fields from an object.n+read-template+: Template for getter functions.n+read-has-opts+,+read-is-opts+,+read-get-opts+: Options for getter methods.ncreate-read-method-form: Creates a method form for reading.nread-getters-form,read-getters,read-all-getters: Reads getter methods.nread-ex: Creates a getter method that throws an exception.nto-data: Converts an object to Clojure data.nto-map: Converts an object to a map.
13.18 std.object.framework.string-like (String-Like Extension)
This sub-namespace provides the implementation for extending Java classes to behave like Clojure strings, allowing for conversion to and from string representations.
Key Functions:
extend-string-like(macro): Extends a class to behave like a string.
13.19 std.object.framework.struct (Struct-Like Access)
This sub-namespace provides functions for accessing object properties in a struct-like manner, using nested maps or vectors to define the access path.
Key Functions:
getter-function: Creates a getter function for a keyword.nfield-function: Creates a field access function.nstruct-getters: Retrieves properties using a getter specification.nstruct-field-functions: Constructs field access functions.nstruct-fields: Retrieves properties using a field specification.nstruct-accessor: Creates an accessor function.ndir: Explores object fields.
13.20 std.object.framework.vector-like (Vector-Like Extension)
This sub-namespace provides the implementation for extending Java classes to behave like Clojure vectors, allowing for sequential access to their elements.
Key Functions:
extend-vector-like(macro): Extends a class to behave like a vector.
13.21 std.object.framework.write (Object Writing)
This sub-namespace provides functions for writing object properties, including metadata, fields, and setter methods, and converting Clojure data structures to Java objects.
Key Functions:
meta-write,meta-write-exact,meta-write-exact?: Accesses and checks write metadata.nwrite-fields,write-all-fields: Writes fields to an object.ncreate-write-method-form: Creates a method form for writing.nwrite-setters-form,write-setters,write-all-setters: Writes setter methods.nwrite-ex: Creates a setter method that throws an exception.nwrite-constructor: Returns a constructor element.nwrite-setter-element: Constructs array elements for setters.nwrite-setter-value: Sets a property given a keyword and value.nfrom-empty: Creates an object from an empty constructor.nfrom-constructor: Creates an object from a constructor.nfrom-map: Creates an object from a map.n*from-data: Creates an object from Clojure data.
13.22 std.object.query (Object Querying)
This sub-namespace provides functions for querying Java classes and objects using reflection, allowing for flexible selection and filtering of members (methods, fields, constructors).
Key Functions:
all-class-members: Returns all raw reflected members of a class.nall-class-elements: Returns allElementrecords for a class.nselect-class-elements: SelectsElementrecords from a class.nquery-class: Queries the Java view of a class.nselect-supers-elements: Selects elements from superclasses.nquery-supers: Queries superclasses.nquery-hierarchy: Queries the entire class hierarchy.nall-instance-elements: Returns all instance elements.nselect-instance-elements: Selects instance elements.nquery-instance: Queries an object instance.nquery-instance-hierarchy: Queries an object instance hierarchy.napply-element: Applies a class element to arguments.ndelegate: Creates a delegate for transparent field access.n*invoke-intern-element: Creates an invoke form for an element.
13.23 std.object.query.filter (Query Filtering)
This sub-namespace provides functions for filtering Element records based on various criteria, such as name, modifiers, parameter types, and origins.
Key Functions:
has-predicate?,has-name?,has-modifier?,has-params?,has-num-params?,has-any-params?,has-all-params?,has-type?,has-origins?: Predicates for filtering.nfilter-by: Filters elements by a given criterion.nfilter-terms-fn: Filters elements based on a group of terms.
13.24 std.object.query.input (Query Input Processing)
This sub-namespace provides utilities for classifying and converting input arguments for object queries.
Key Functions:
args-classify: Classifies input arguments.nargs-convert: Converts arguments to primitive classes.nargs-group: Groups input arguments into categories.
13.25 std.object.query.order (Query Ordering)
This sub-namespace provides functions for sorting and ordering Element records based on various criteria.
Key Functions:
sort-fn: Creates a sorting function.nsort-terms-fn: Sorts elements by terms.nfirst-terms-fn: Returns the first element.nmerge-terms-fn: Merges elements.nselect-terms-fn: Selects terms to output.n*order: Orders elements based on a group of terms.
13.26 Usage Pattern:
The std.object module is essential for:
- Java Interoperability: Seamlessly interacting with Java objects and classes from Clojure.n Metaprogramming: Dynamically inspecting and manipulating Java objects at runtime.n Framework Development: Building extensible frameworks that can adapt to different Java object models.n Data Conversion: Converting between Java objects and Clojure data structures.n Reflection-Based Tools: Creating tools that analyze and interact with Java code.
By providing a powerful and flexible object introspection and manipulation framework, std.object empowers developers to leverage the full power of the Java ecosystem within their Clojure applications.
14 std.pretty: A Comprehensive Summary (including submodules)
The std.pretty module provides a powerful and extensible pretty-printing framework for Clojure, designed to render complex data structures in a human-readable and customizable format. It supports features like intelligent line wrapping, syntax highlighting with ANSI colors, and custom handlers for various data types. This module is crucial for debugging, logging, and generating formatted output in Clojure applications.
14.1 std.pretty (Main Namespace)
This namespace serves as the primary entry point for pretty-printing, aggregating and re-exporting key functionalities from its submodules. It defines the core pretty-printing options and provides high-level functions for rendering data.
Core Concepts:
+defaults+: A map defining default pretty-printing options, including width, key sorting, collection delimiters, color settings, and fallback behaviors.nCanonicalPrinter: A printer implementation that produces a canonical, uncolored representation of data.nPrettyPrinter: A printer implementation that applies all pretty-printing options, including coloring and custom handlers.
Key Functions:
format-unknown: Formats unknown data types.nformat-doc-edn: Formats EDN-like data.nformat-doc: The main function for formatting data into a document.npr-handler: A print handler for printing strings.nunknown-handler: A handler for unknown objects.ntagged-handler: A handler for tagged literals.njava-handlers,clojure-handlers,clojure-interface-handlers,common-handlers: Collections of predefined print handlers for Java and Clojure types.ncanonical-printer: Creates a canonical printer.npretty-printer: Creates a pretty printer.nrender-out: Renders a document to an output stream.npprint: Pretty-prints a value to*out*.npprint-str: Returns the pretty-printed string.npprint-cc: Pretty-prints using thestd.concurrent.printframework.
14.2 std.pretty.color (Coloring Utilities)
This sub-namespace provides utilities for applying color and other markup to text, supporting ANSI escape codes, inline HTML styles, and HTML classes.
Key Functions:
-document(multimethod): Constructs a pretty-print document with optional coloring.n*-text(multimethod): Produces colored text.
14.3 std.pretty.compare (Comparison Utilities)
This sub-namespace provides a custom comparison function for various Clojure data types, used for sorting keys in maps and sets during pretty-printing.
Key Functions:
type-priority: Assigns a priority to different data types for comparison.ncompare-seqs: Compares two sequences.ncompare: Compares any two values, handling different types and collections.
14.4 std.pretty.deque (Deque Implementation)
This sub-namespace provides a simple deque (double-ended queue) implementation using clojure.core.rrb-vector, used internally by the pretty-printing engine.
Key Functions:
pop-left,peek-left: Removes or peeks at the leftmost element.nconj-right,conj-left,conj-both: Adds elements to either end.nupdate-left,update-right: Updates elements at either end.
14.5 std.pretty.dispatch (Dispatch Mechanisms)
This sub-namespace provides mechanisms for dispatching print handlers based on class inheritance, allowing for flexible and extensible type-based printing.
Key Functions:
chained-lookup: Chains multiple lookup functions together.n*inheritance-lookup: Creates a lookup function that considers class inheritance.
14.6 std.pretty.edn (EDN Printing)
This sub-namespace provides the core logic for visiting and formatting EDN (Extensible Data Notation) data structures, including primitive types, collections, and tagged literals.
Key Functions:
override?: Checks if an object implementsprotocol.pretty/IOverride.nedn: Converts an object to an EDN representation.nclass->edn: Converts aClassobject to its EDN representation.ntagged-object: Converts an object to a tagged literal.nformat-date: Formats a date object.n*visit-seq,visit-tagged,visit-unknown,visit-meta,visit-edn,visit: Functions for visiting and formatting different EDN data types.
14.7 std.pretty.engine (Pretty-Printing Engine)
This sub-namespace implements the core pretty-printing algorithm, which converts a document (a hierarchical data structure representing the formatted output) into a flat sequence of operations, and then renders these operations to a string.
Key Functions:
serialize: Converts a document into a sequence of operations.nserialize-node-text,serialize-node-pass,serialize-node-escaped,serialize-node-span,serialize-node-line,serialize-node-break,serialize-node-group,serialize-node-nest,serialize-node-align: Functions for serializing different types of document nodes.nannotate-right: Annotates nodes with their rightmost position.nannotate-begin: Recalculates the rightmost position ofbeginnodes.nformat-nodes: Formats nodes given a line width.n*pprint-document: Pretty-prints a document to an output stream.
14.8 std.pretty.protocol (Pretty-Printing Protocols)
This sub-namespace defines the core protocols and multimethods that enable extensible pretty-printing, allowing custom handlers for various data types and output formats.
Key Protocols:
IEdn: Defines the-ednmethod for converting an object to an EDN representation.nIOverride: A marker protocol for types that override default printing behavior.nIVisitor: Defines methods for visiting and formatting different EDN data types.
Key Multimethods:
-serialize-node: Serializes a document node.n-document: Constructs a pretty-print document.n-text: Produces colored text.
14.9 Usage Pattern:
The std.pretty module is essential for:
- Debugging: Making complex data structures easier to understand in logs and console output.n User Interfaces: Generating formatted text for display in terminal-based or HTML-based applications.n Code Generation: Producing human-readable code output.n* Documentation: Formatting code examples and data structures.
By providing a flexible and powerful pretty-printing solution, std.pretty enhances the developer experience and improves the readability of Clojure applications.
15 std.print: A Comprehensive Summary (including submodules)
The std.print module provides a comprehensive set of utilities for formatted output in Clojure, focusing on enhancing readability and presentation in various contexts, including console, reports, and animated displays. It builds upon ANSI escape codes for terminal styling and offers flexible formatting options for different data types and structures.
15.1 std.print (Main Namespace)
This namespace serves as the primary entry point for formatted printing, aggregating and re-exporting key functionalities from its submodules. It provides high-level functions for printing various types of reports and styled output.
Key Re-exported Functions:
- From
std.concurrent.print:print,println,with-out-str,prn.n* Fromstd.print.base.report:print-header,print-row,print-title,print-subtitle,print-column,print-summary,print-tree-graph.
15.2 std.print.ansi (ANSI Styling)
This sub-namespace provides functions for generating ANSI escape codes to style text in terminal environments, including colors, highlights, and text attributes.
Core Concepts:
+colors+,+highlights+,+attributes+: Maps defining ANSI codes for various text properties.n*+lookup+: A reverse lookup map for ANSI codes.
Key Functions:
encode-raw: Encodes raw ANSI modifier codes to a string.nencode: Encodes ANSI characters for modifiers (e.g.,:bold,:red).nstyle: Styles text with ANSI modifiers.nstyle:remove: Removes ANSI formatting from a string.ndefine-ansi-forms(macro): Defines helper functions for common ANSI styles (e.g.,blue,on-white,bold).
15.3 std.print.base.animate (Animation)
This sub-namespace provides utilities for displaying ASCII animations in the console.
Key Functions:
print-animation: Outputs an animated ASCII file or a sequence of frames.
15.4 std.print.base.report (Report Generation)
This sub-namespace provides functions for generating structured reports, including headers, titles, rows, columns, and summaries.
Key Functions:
print-header: Prints a report header.nprint-title: Prints a report title.nprint-subtitle: Prints a report subtitle.nprint-row: Prints a row of data.nprint-column: Prints a column of data.nprint-summary: Prints a summary of results.nprint-tree-graph: Prints a tree-like graph.
15.5 std.print.format (General Formatting)
This sub-namespace aggregates various formatting utilities from its submodules, providing a unified interface for common formatting tasks.
Key Functions:
- From
std.print.format.chart:bar-graph,tree-graph,sparkline,table,table:parse.n Fromstd.print.format.common:pad,pad:left,pad:right,pad:center,justify,border,indent.n Fromstd.print.format.report:report:bold,report:column,report:header,report:row,report:title.n* Fromstd.print.format.time:t,t:ms,t:ns,t:time.
15.6 std.print.format.chart (Chart Formatting)
This sub-namespace provides functions for formatting various types of ASCII charts and tables for console output.
Key Functions:
lines:bar-graph: Formats an ASCII bar graph as lines.nbar-graph: Constructs an ASCII bar graph.nsparkline: Formats a sparkline.ntree-graph: Returns a string representation of a tree graph.ntable-basic:format: Generates a basic ASCII table.ntable-basic:parse: Reads a basic ASCII table from a string.ntable: Generates a formatted ASCII table.n*table:parse: Parses a formatted ASCII table.
15.7 std.print.format.common (Common Formatting Utilities)
This sub-namespace provides fundamental utilities for padding, justifying, indenting, and bordering text.
Key Functions:
pad,pad:left,pad:right,pad:center: Functions for padding text.njustify: Justifies text to a given alignment.nindent: Indents lines of text.npad:lines: Creates new lines of spaces.nborder: Formats a border around lines of text.
15.8 std.print.format.report (Report Formatting)
This sub-namespace provides functions for formatting elements within reports, such as rows, headers, and titles.
Key Functions:
lines:elements: Lays out an array of elements as rows.nlines:row-basic: Lays out raw elements for a row.nlines:row: Lays out row elements with colors and results.nreport:header: Formats a report header.nreport:row: Formats a report row.nreport:title: Formats a report title.nreport:bold: Formats text in bold.n*report:column: Formats a report column.
15.9 std.print.format.time (Time Formatting)
This sub-namespace provides functions for formatting time and duration values into human-readable strings, with optional styling.
Key Functions:
t:time: Formats a timestamp to time only.nt:ms: Converts milliseconds to a human-readable duration.nt:ns: Converts nanoseconds to a human-readable duration.nt:text: Formats nanoseconds to a string.nt:style: Sets the color for a time duration.n*t: Formats nanoseconds to a styled string.
15.10 std.print.progress (Progress Indicators)
This sub-namespace provides utilities for displaying progress indicators in the console, including progress bars and spinners.
Key Functions:
replace-center: Replaces the center of a string with text.nprogress-bar-string: Converts a progress percentage to a progress bar string.nprogress-spinner-string: Converts progress to a spinner string.nprogress-eta: Calculates the estimated time left.nprogress: Creates a progress structure.nprogress-string: Creates a string representation of progress.nprogress-update: Updates the progress meter.n*progress-test: Demonstrates progress indicators.
15.11 Usage Pattern:
The std.print module is essential for:
- User Feedback: Providing clear and informative output to users in console applications.n Debugging and Logging: Enhancing the readability of debug messages and log entries.n Reporting: Generating structured reports and summaries.n* Visualizations: Creating simple ASCII charts and progress indicators.
By offering a rich set of formatting and presentation tools, std.print improves the user experience and makes console-based applications more engaging and informative.
16 std.protocol: A Comprehensive Summary
The std.protocol module in foundation-base defines a comprehensive set of Clojure protocols and multimethods that establish a standardized interface for various functionalities across the ecosystem. These protocols serve as contracts, enabling polymorphic behavior and allowing different implementations to adhere to a common API. This modular design promotes extensibility, maintainability, and interoperability within the project.
The module is organized into several sub-protocols, each addressing a specific domain:
16.1 std.protocol.apply
Defines an interface for objects that can be "applied" or invoked within a runtime context, allowing for transformation of input and output.
IApplicableProtocol:n-apply-in [app rt args]: Applies the object within a runtimertwithargs.n-apply-default [app]: Provides a default application behavior.n-transform-in [app rt args]: Transforms input arguments before application.n-transform-out [app rt args return]: Transforms the return value after application.
16.2 std.protocol.archive
Defines an interface for interacting with archive files (e.g., ZIP, JAR), providing functionalities for listing, checking, archiving, extracting, inserting, removing, writing, and streaming entries.
IArchiveProtocol:n-url [archive]: Returns the URL of the archive.n-path [archive entry]: Returns the path of an entry within the archive.n-list [archive]: Lists all entries in the archive.n-has? [archive entry]: Checks if an entry exists in the archive.n-archive [archive root inputs]: Creates an archive frominputsatroot.n-extract [archive output entries]: Extractsentriesfrom the archive tooutput.n-insert [archive entry input]: Inserts aninputas anentryinto the archive.n-remove [archive entry]: Removes anentryfrom the archive.n-write [archive entry stream]: Writes anentryto astream.n-stream [archive entry]: Returns an input stream for anentry.n-openMultimethod:n Dispatches ontypeandpath, allowing different implementations for opening various archive types (e.g.,:zip,:jar).
16.3 std.protocol.binary
Defines interfaces for converting objects to and from binary representations, and for handling byte sources, sinks, and channels.
IBinaryProtocol:n-to-bitstr [x]: Convertsxto a bit string.n-to-bitseq [x]: Convertsxto a sequence of bits.n-to-bitset [x]: Convertsxto a set of bits.n-to-bytes [x]: Convertsxto a byte array.n-to-number [x]: Convertsxto a number.nIByteSourceProtocol:n-to-input-stream [obj]: Convertsobjto anInputStream.nIByteSinkProtocol:n-to-output-stream [obj]: Convertsobjto anOutputStream.nIByteChannelProtocol:n *-to-channel [obj]: Convertsobjto ajava.nio.channels.Channel.
16.4 std.protocol.block
Defines interfaces for representing and manipulating code as data structures ("blocks"), forming the Abstract Syntax Tree (AST) or Intermediate Representation (IR) of the transpiler.
IBlockInterface:n_type []: Returns the block's type (e.g.,:list,:symbol).n_tag []: Returns the semantic tag of the block.n_string []: Converts the block to its string representation.n_length []: Returns the length of the block.n_width []: Returns the width (rows) of the block.n_height []: Returns the height (columns) of the block.n_prefixed []: Returns the length of the prefix.n_suffixed []: Returns the length of the suffix.n_verify []: Checks if the block contains valid data.nIBlockModifierInterface:n_modify [accumulator input]: Modifies an accumulator with an input block.nIBlockExpressionInterface:n_value []: Returns the semantic value of the block.n_value_string []: Returns the string representation of the block's value.nIBlockContainerInterface:n_children []: Returns the children of a container block.n *_replace_children [children]: Replaces the children of a container block.
16.5 std.protocol.component
Defines interfaces for managing the lifecycle and querying the state of components within the system.
IComponentProtocol:n-start [component]: Starts the component.n-stop [component]: Stops the component gracefully.n-kill [component]: Forcefully stops the component.nIComponentQueryProtocol:n-started? [component]: Checks if the component is started.n-stopped? [component]: Checks if the component is stopped.n-info [component level]: Returns information about the component at a given level of detail.n-remote? [component]: Checks if the component is a remote resource.n-health [component]: Returns the health status of the component.nIComponentPropsProtocol:n-props [component]: Returns the properties of the component.nIComponentOptionsProtocol:n-get-options [component]: Returns the options configured for the component.nIComponentTrackProtocol:n *-get-track-path [component]: Returns the tracking path for the component.
16.6 std.protocol.context
Defines interfaces for managing execution contexts, pointers to resources within those contexts, and their lifecycle.
ISpaceProtocol:n-context-set [sp ctx key options]: Sets a context.n-context-unset [sp ctx]: Unsets a context.n-context-list [sp]: Lists available contexts.n-context-get [sp ctx]: Retrieves a context.n-rt-active [sp]: Returns the active runtime.n-rt-get [sp ctx]: Retrieves a runtime.n-rt-start [sp ctx]: Starts a runtime.n-rt-started? [sp ctx]: Checks if a runtime is started.n-rt-stopped? [sp ctx]: Checks if a runtime is stopped.n-rt-stop [sp ctx]: Stops a runtime.nIPointerProtocol:n-ptr-context [_]: Returns the context of a pointer.n-ptr-keys [ptr]: Returns the keys associated with a pointer.n-ptr-val [ptr key]: Returns the value for a key in a pointer.nIContextProtocol:n-raw-eval [rt string]: Evaluates a raw string in the runtime.n-init-ptr [rt ptr]: Initializes a pointer in the runtime.n-tags-ptr [rt ptr]: Tags a pointer.n-deref-ptr [rt ptr]: Dereferences a pointer.n-display-ptr [rt ptr]: Displays a pointer.n-invoke-ptr [rt ptr args]: Invokes a pointer with arguments.n-transform-in-ptr [rt ptr args]: Transforms input arguments for a pointer.n-transform-out-ptr [rt ptr return]: Transforms the return value from a pointer.nIContextLifeCycleProtocol:n-has-module? [rt module-id]: Checks if a module exists in the runtime.n-setup-module [rt module-id]: Sets up a module in the runtime.n-teardown-module [rt module-id]: Tears down a module in the runtime.n-has-ptr? [rt ptr]: Checks if a pointer exists in the runtime.n-setup-ptr [rt ptr]: Sets up a pointer in the runtime.n-teardown-ptr [rt ptr]: Tears down a pointer in the runtime.
16.7 std.protocol.deps
Defines interfaces for managing dependencies, including retrieving entries, compiling, and tearing down dependency graphs.
IDepsProtocol:n-get-entry [context id]: Retrieves a dependency entry.n-get-deps [context id]: Retrieves dependencies for an entry.n-list-entries [context]: Lists all dependency entries.nIDepsMutateProtocol:n-add-entry [context id entry deps]: Adds a dependency entry.n-remove-entry [context id]: Removes a dependency entry.n-refresh-entry [context id]: Refreshes a dependency entry.nIDepsCompileProtocol:n-step-construct [context acc id]: Constructs a dependency step.n-init-construct [context]: Initializes dependency construction.nIDepsTeardownProtocol:n-step-deconstruct [context acc id]: Deconstructs a dependency step.nIDepsLibraryProtocol:n-parse-native [context input opts]: Parses native input for the dependency library.nIDepsProducerProtocol:n-produce [context opts]: Produces dependencies.n-createMultimethod:n Dispatches on:path, used for creating dependency contexts.
16.8 std.protocol.dispatch
Defines interfaces for dispatching tasks, typically to executors or queues.
IDispatchProtocol:n-submit [dispatch entry]: Submits an entry for dispatch.n-bulk? [dispatch]: Checks if the dispatch mechanism supports bulk operations.n-createMultimethod:n Dispatches on:type, used for creating dispatch executors.
16.9 std.protocol.invoke
Defines multimethods for handling function invocation, package loading, and anonymous function body generation, particularly relevant for code generation and dynamic execution.
-invoke-internMultimethod:n Dispatches onlabel,name,config,body, used for constructing forms for interning invoked functions.n-invoke-packageMultimethod:n Dispatches onidentity, used for loading invoke-intern types.n-fn-bodyMultimethod:n Dispatches onlabelandbody, used for defining anonymous function bodies (e.g., for different target languages).n-fn-packageMultimethod:n * Dispatches onidentity, used for loadingfn-bodytypes.
16.10 std.protocol.log
Defines interfaces for logging, including writing log entries and processing them.
ILoggerProtocol:n-logger-write [logger entry]: Writes a log entry.nILoggerProcessProtocol:n-logger-process [logger entries]: Processes a collection of log entries.n-createMultimethod:n * Dispatches on:type, used for creating logger instances.
16.11 std.protocol.match
Defines an interface for template matching.
ITemplateProtocol:n *-match [template obj]: Matches an object against a template.
16.12 std.protocol.object
Defines multimethods for accessing and manipulating object metadata, particularly for reading and writing.
-meta-readMultimethod:n Dispatches onidentity, used for accessing class meta information for reading from an object.n-meta-writeMultimethod:n * Dispatches onidentity, used for accessing class meta information for writing to an object.
16.13 std.protocol.request
Defines interfaces for making single or bulk requests and processing their responses.
IRequestProtocol:n-request-single [client command opts]: Makes a single request.n-process-single [client output opts]: Processes a single request's output.n-request-bulk [client commands opts]: Makes multiple requests in bulk.n-process-bulk [client inputs outputs opts]: Processes bulk request inputs and outputs.nIRequestTransactProtocol:n-transact-start [client]: Starts a transaction.n-transact-end [client]: Ends a transaction.n-transact-combine [client commands]: Combines commands within a transaction.
16.14 std.protocol.return
Defines an interface for handling return values, including checking for errors and retrieving metadata.
IReturnProtocol:n-get-value [obj]: Retrieves the value from a return object.n-get-error [obj]: Retrieves any error from a return object.n-has-error? [obj]: Checks if the return object contains an error.n-get-status [obj]: Retrieves the status of the return object.n-get-metadata [obj]: Retrieves metadata associated with the return object.n-is-container? [obj]: Checks if the return object is a container.
16.15 std.protocol.state
Defines interfaces and multimethods for managing state, including creation, retrieval, update, and cloning.
IStateGetProtocol:n-get-state [obj opts]: Retrieves the state of an object.nIStateSetProtocol:n-update-state [obj f args opts]: Updates the state of an object using a functionf.n-set-state [obj v opts]: Sets the state of an object tov.n-empty-state [obj opts]: Empties the state of an object.n-clone-state [obj opts]: Clones the state of an object.n-create-stateMultimethod:n Dispatches ontype,data,opts, used for creating state objects.n-container-stateMultimethod:n Dispatches onidentity, used for returning a type for a label.
16.16 std.protocol.stream
Defines interfaces for stream-like operations, including collecting, producing, blocking, and staging.
ISinkProtocol:n-collect [sink xf supply]: Collects items into a sink.nISourceProtocol:n-produce [source]: Produces items from a source.nIBlockingProtocol:n-take-element [source]: Takes an element from a blocking source.nIStageProtocol:n-stage-unit [stage]: Returns the unit of a stage.n-stage-realized? [stage]: Checks if a stage is realized.n *-stage-realize [stage]: Realizes a stage.
16.17 std.protocol.string
Defines interfaces and multimethods for string conversions and path separation.
IStringProtocol:n-to-string [x]: Convertsxto a string.n-from-stringMultimethod:n Dispatches onstring,type,opts, used for extending string-like objects.n-path-separatorMultimethod:n * Dispatches onidentity, used for finding the path separator for a given data type.
16.18 std.protocol.time
Defines interfaces and multimethods for handling time instants, durations, representations, and formatting/parsing.
IInstantProtocol:n-to-long [t]: Converts a time instanttto a long.n-has-timezone? [t]: Checks ifthas timezone information.n-get-timezone [t]: Gets the timezone oft.n-with-timezone [t tz]: Sets the timezone oft.nIRepresentationProtocol:n-millisecond [t opts]: Gets the millisecond component oft.n-second [t opts]: Gets the second component oft.n-minute [t opts]: Gets the minute component oft.n-hour [t opts]: Gets the hour component oft.n-day [t opts]: Gets the day component oft.n-day-of-week [t opts]: Gets the day of the week component oft.n-month [t opts]: Gets the month component oft.n-year [t opts]: Gets the year component oft.nIDurationProtocol:n-to-length [d opts]: Converts a durationdto a length.n-time-metaMultimethod:n Dispatches oncls, used for accessing meta properties of a class related to time.n-from-longMultimethod:n Dispatches onlong,opts(specifically:type), used for creating time representations from a long.n-nowMultimethod:n Dispatches onopts(specifically:type), used for creating a representation of the current time.n-from-lengthMultimethod:n Dispatches onlong,opts(specifically:type), used for creating a representation of a duration.n-formatterMultimethod:n Dispatches onpattern,opts(specifically:type), used for creating time formatters.n-formatMultimethod:n Dispatches onformatter,t,opts, used for formatting time objects.n-parserMultimethod:n Dispatches onpattern,opts(specifically:type), used for creating time parsers.n-parseMultimethod:n * Dispatches onparser,s,opts(specifically:type), used for parsing time strings.
16.19 std.protocol.track
Defines an interface for tracking components.
ITrackProtocol:n *-track-path [component]: Returns the tracking path for a component.
16.20 std.protocol.watch
Defines an interface for adding, removing, and listing watches on objects.
IWatchProtocol:n-add-watch [obj k f opts]: Adds a watch to an object.n-has-watch [obj k opts]: Checks if an object has a specific watch.n-remove-watch [obj k opts]: Removes a watch from an object.n-list-watch [obj opts]: Lists all watches on an object.
16.21 std.protocol.wire
Defines interfaces and multimethods for wire-level communication, including reading, writing, closing, and serialization/deserialization of data.
IWireProtocol:n-read [remote]: Reads from a remote connection.n-write [remote command]: Writes a command to a remote connection.n-close [remote]: Closes a remote connection.n-as-inputMultimethod:n Dispatches onval,type, used for converting an object to an input format.n-serialize-bytesMultimethod:n Dispatches onval,type, used for converting an object to bytes.n-deserialize-bytesMultimethod:n * Dispatches onbytes,type, used for converting bytes back to an object.
Overall Importance:
The std.protocol module is central to the foundation-base project's architectural design. By defining clear, extensible interfaces, it enables:
- Polymorphism: Different data types and implementations can adhere to the same behavioral contracts, promoting code reuse and flexibility.n Modularity: Functionalities are decoupled from concrete implementations, making it easier to swap out or add new components without affecting the entire system.n Extensibility: New types can easily extend existing protocols, allowing the system to evolve and adapt to new requirements.n Testability: Protocols provide well-defined boundaries, simplifying the testing of individual components.n Clarity and Documentation: Protocols serve as self-documenting APIs, clearly outlining the expected behavior of various system parts.
This comprehensive set of protocols forms the backbone of foundation-base, facilitating its advanced capabilities in transpilation, runtime management, and multi-language support.
17 std.text: A Comprehensive Summary
The std.text module in foundation-base provides functionalities for text processing, specifically focusing on text differencing and full-text indexing. It integrates with external libraries (like difflib for Java) and offers tools for comparing text, applying/reverting patches, and creating searchable text indexes with stemming and persistence capabilities.
The module is organized into two main sub-namespaces:
17.1 std.text.diff
This namespace provides utilities for computing and applying differences between text sequences, often referred to as "diffing" and "patching." It leverages the difflib Java library.
create-patch [arr]: Creates adifflib.Patchobject from a collection of delta maps.nobject/vector-like Patch: Extendsdifflib.Patchto be treated as a vector-like object, allowing conversion to/from data maps.nobject/string-like Delta$TYPE: Extendsdifflib.Delta$TYPEto be treated as a string-like object, allowing conversion to/from string representations.ncreate-delta [map]: Creates adifflib.Deltaobject (e.g.,InsertDelta,ChangeDelta,DeleteDelta) from a map representation.nobject/map-like Delta: Extendsdifflib.Deltato be treated as a map-like object, allowing conversion to/from data maps.ncreate-chunk [map]: Creates adifflib.Chunkobject from a map representation.nobject/map-like Chunk: Extendsdifflib.Chunkto be treated as a map-like object, allowing conversion to/from data maps.ndiff [original revised]: Computes the differences between two text strings (or sequences of lines) and returns a collection of delta maps.npatch [original diff]: Applies a series ofdiffdeltas to anoriginaltext, returning therevisedtext.nunpatch [revised diff]: Reverts a series ofdiffdeltas from arevisedtext, restoring theoriginaltext.n->string [deltas]: Converts a collection of delta maps into a human-readable string representation, often with ANSI color coding for added/removed lines.n*summary [deltas]: Creates a summary of the diffs, counting the number of deletions and insertions.
17.2 std.text.index
This namespace provides functionalities for creating and querying a full-text search index, including text stemming and disk persistence. It uses std.text.index.stemmer and std.text.index.porter for stemming.
IndexRecord: A Clojure record to hold the index data (a map from stem to a map of keys to weights) and the stemmer function.nmake-index [& [stemmer-func]]: Creates a new search index, optionally specifying a custom stemmer function (defaults to Porter stemmer). The index is managed as an agent for concurrent updates.nadd-entry [index stem key weight]: Adds an entry to the index for a given stem, associating it with akeyandweight.nremove-entries [index key stems]: Removes entries associated with akeyfor a given set ofstems.nindex-text [index key data & [weight]]: Adds text to the index. It processes text blocks, stems words, calculates frequencies, and updates the index with associated keys and weights.nunindex-text [index key txt]: Removes text associated with akeyfrom the index.nunindex-all [index key]: Clears all entries associated with a specifickeyfrom the index.nquery [index query-string]: Queries the index with aquery-string, returning a map of stems to their associated key-weight maps.nmerge-and [query-results]: Merges query results using an "AND" logic, returning a map of IDs to their combined scores (multiplied weights).nmerge-or [query-results]: Merges query results using an "OR" logic, returning a map of IDs to their combined scores (summed weights).nsearch [index term & [merge-style]]: Performs a search on the index for a giventerm, using either "AND" (default) or "OR" merge style, and returns sorted results.nsave-index [index & [filename-or-file]]: Saves the index data to a file, optionally specifying the filename.nload-index [index filename-or-file]: Loads index data from a file into the index.
Overall Importance:
The std.text module is a valuable component for applications requiring text analysis, comparison, and search capabilities within the foundation-base project.
- Text Differencing: The
std.text.diffnamespace is crucial for tasks like version control, code review tools, or any application that needs to highlight changes between text documents. Its integration withdifflibprovides robust diffing algorithms, and the->stringfunction offers user-friendly output.n Full-Text Search: Thestd.text.indexnamespace provides a lightweight yet powerful full-text indexing solution. This is essential for applications that need to search through large volumes of text efficiently, such as documentation systems, knowledge bases, or code search tools. The use of stemming improves search relevance, and agent-based concurrency ensures safe updates.n Foundation for Text-Based Tools: Both sub-modules provide foundational building blocks for creating more sophisticated text-based tools and features within thefoundation-baseecosystem, supporting its broader goals of code generation and language processing.
By offering these specialized text processing functionalities, std.text enhances the project's ability to manage and interact with textual data effectively.