Module functions

Source
Expand description

Built-in function library for AIM expressions.

This module provides a comprehensive collection of built-in functions organized by category to extend the capabilities of AIM expressions. Functions can be called directly as function_name(args) or as methods on values like array.sum().

§Overview

The function library is designed to provide spreadsheet-like functionality with the power of a programming language. Functions are organized into logical categories and can be composed together to create complex expressions.

§Function Categories

The function library is organized into the following categories:

§Business Functions

Financial calculations, growth analysis, and business metrics.

  • round_to(number, decimals) - Round with decimal control
  • percent_of(number, total) - Calculate percentage of total
  • increase(number, percent) - Increase by percentage
  • decrease(number, percent) - Decrease by percentage
  • gross_margin(cost, price) - Calculate gross margin
  • markup(cost, percent) - Apply markup to cost
  • growth(from, to) - Calculate period-over-period growth
  • runway(funding, expenses) - Calculate runway based on funding and expenses
  • monthly_payment(principal, rate, years) - Calculate monthly loan payment
  • break_even(fixed_costs, price, variable_cost) - Calculate break-even point
  • roi(investment, return_amount) - Calculate Return on Investment
  • split_amount(percentages, total) - Split amount across percentages
  • tax_inclusive(amount, tax_rate) - Calculate tax-inclusive amount
  • tax_exclusive(amount, tax_rate) - Calculate tax-exclusive amount

§Collection Functions

Array manipulation, filtering, and transformation functions.

  • len(array) - Length of array or string
  • count(array) - Count of array elements
  • find(array, closure) - Returns the first element that satisfies a predicate
  • find_index(array, closure) - Returns the index of the first element that satisfies a predicate
  • flatten(array) - Flatten nested arrays
  • unique(array) - Get unique elements from single array
  • reverse(array) - Reverse array
  • take(array, count) - Get first n elements
  • take_right(array, count) - Get last n elements
  • skip(array, count) - Skip first n elements
  • skip_right(array, count) - Skip last n elements
  • chunk(array, size) - Chunk array into groups of n
  • group_by(array, closure) - Group elements by key from closure
  • partition(array, closure) - Partition array into two based on predicate
  • sort_by(array, closure) - Sort array by closure
  • all_unique(array) - Check if all elements are unique
  • take_while(array, closure) - Take elements while predicate is true
  • skip_while(array, closure) - Skip elements while predicate is true
  • zip(array1, array2) - Zip two arrays together into pairs
  • unzip(pairs) - Unzip array of pairs into two arrays

§Date Functions

Date parsing, formatting, and calculation functions.

  • as_date(text, format) - Parse text as date
  • format_date(date, format) - Format date as text
  • days_between(date1, date2) - Calculate days between dates
  • add_days(date, days) - Add days to date
  • workdays(date1, date2) - Calculate workdays between dates
  • Date methods:
    • date.year() - Year component
    • date.month() - Month component
    • date.day() - Day component
    • date.hour() - Hour component
    • date.minute() - Minute component
    • date.second() - Second component

§Functional Programming Support

Higher-order functions for functional programming patterns.

  • map(array, closure) - Apply closure to each element of array
  • select(array, closure) - Like map but also provides the index to the closure
  • filter(array, closure) - Filter array elements using predicate closure
  • reduce(array, initial, closure) - Reduce array to single value using accumulator closure
  • scan(array, initial, closure) - Like reduce but keeps intermediate results
  • some(array, closure) - Returns true if any element satisfies the predicate
  • every(array, closure) - Returns true if all elements satisfy the predicate
  • none(array, closure) - Returns true if no elements satisfy the predicate
  • exactly_one(array, closure) - Returns true if exactly one element satisfies the predicate

§Mathematical Functions

Basic arithmetic, trigonometric, logarithmic, and advanced mathematical operations.

  • abs(x) - Absolute value
  • sign(x) - Sign of number
  • floor(x) - Floor function
  • ceil(x) - Ceiling function
  • round(x) - Round to nearest integer
  • trunc(x) - Truncate decimal places
  • sqrt(x) - Square root
  • pow(base, exp) - Power function
  • exp(x) - e^x
  • ln(x) - Natural logarithm
  • log10(x) - Base 10 logarithm
  • log2(x) - Base 2 logarithm
  • sin(x) - Sine function
  • cos(x) - Cosine function
  • tan(x) - Tangent function
  • asin(x) - Arc sine
  • acos(x) - Arc cosine
  • atan(x) - Arc tangent
  • atan2(y, x) - Arc tangent with two arguments
  • sinh(x) - Hyperbolic sine
  • cosh(x) - Hyperbolic cosine
  • tanh(x) - Hyperbolic tangent
  • random() - Random number between 0 and 1
  • clamp(x, min, max) - Constrain to range
  • lerp(a, b, t) - Linear interpolation
  • gcd(a, b) - Greatest common divisor
  • lcm(a, b) - Least common multiple
  • is_nan(x) - Check if NaN
  • is_finite(x) - Check if finite
  • PI() - Mathematical constant π
  • E() - Mathematical constant e
  • NaN() - Not-a-number value

§Number Functions

Number formatting and conversion utilities.

  • ordinal(number) - Convert number to ordinal (1st, 2nd, etc.)
  • format_currency(number, symbol) - Format as currency
  • format_number(number, decimals) - Format with specified decimals

§Set Functions

Set operations on arrays.

  • union(array1, array2) - Returns the union of two arrays (unique elements from both)
  • intersection(array1, array2) - Returns the intersection of two arrays (elements common to both)
  • difference(array1, array2) - Returns elements in first array that are not in second array
  • exclusive(array1, array2) - Elements in either array but not both
  • is_subset(array1, array2) - Check if first array is subset of second array
  • set_equals(array1, array2) - Check if arrays are equal as sets (ignoring order)
  • overlaps(array1, array2) - Check if arrays have any common elements

§Statistical Functions

Descriptive statistics, trend analysis, and data processing.

  • min(array) - Minimum value in array
  • max(array) - Maximum value in array
  • sum(array) - Sum of array values
  • average(array) - Average of array values
  • avg(array) - Average of array values
  • median(array) - Median value
  • mode(array) - Mode value
  • range(array) - Range of values
  • stdev(array) - Standard deviation
  • variance(array) - Variance
  • percentile(array, percentage) - Percentile value
  • quartile(array, quartile) - Quartile value (1, 2, or 3)
  • growth_rate(from, to) - Growth rate calculation
  • slope(x_values, y_values) - Linear regression slope
  • correlation(x_values, y_values) - Pearson correlation coefficient
  • moving_average(array, period) - Moving average
  • cumulative_sum(array) - Cumulative sum array
  • rank(array, value) - Rank of value in array
  • percentile_rank(array, value) - Percentile rank of value
  • outliers(array) - Array of outlier values
  • frequency(array, bins) - Frequency distribution
  • unique_count(array) - Count of unique values
  • Various count functions:
    • count_if_gt(array, threshold) - Count values > threshold
    • count_if_ge(array, threshold) - Count values >= threshold
    • count_if_lt(array, threshold) - Count values < threshold
    • count_if_le(array, threshold) - Count values <= threshold
    • count_if(array, value) - Count values equal to value
    • count_if_ne(array, value) - Count values not equal to value
  • confidence(alpha, stdev, size) - Confidence interval
  • margin_of_error(array, alpha) - Margin of error

§Task Functions

Task creation and management for agentic workflows.

  • task(text) - Create a new pending task with the text expression
  • perform(tasks, attempts, closure) - Perform pending tasks one by one with retry attempts
  • follow(plan, closure) - Like perform, but with entire plan (tasks).
  • Task methods:
    • task.done() - Mark task as completed
    • task.pending() - Mark task as pending
    • task.failed() - Mark task as failed

§Text Functions

String manipulation, formatting, and analysis functions.

  • concat(array) - Concatenate array of strings
  • join_with(array, sep) - Join array with separator
  • split(text, delim) - Split text into array
  • substring(text, start, len) - Extract substring
  • upper(text) - Convert to uppercase
  • lower(text) - Convert to lowercase
  • proper(text) - Convert to proper case
  • trim(text) - Trim whitespace
  • contains(text, sub) - Check if contains substring
  • replace(text, old, new) - Replace first occurrence
  • replace_all(text, old, new) - Replace all occurrences
  • starts_with(text, prefix) - Check if starts with prefix
  • ends_with(text, suffix) - Check if ends with suffix
  • if_empty(text, default) - Return default if empty
  • pluralize(text, count, suffix) - Pluralize text
  • truncate(text, len, suffix) - Truncate text
  • mask_sensitive(text, start, end) - Mask sensitive data

§Miscellaneous Functions

Debugging and development utilities.

  • debug(value) - Print value to stderr and return unchanged (useful for debugging expressions)

§Evaluation Functions

Evaluation tracking and performance monitoring for agentic workflows.

  • pass(eval) - Record successful evaluation attempt
  • fail(eval) - Record failed evaluation attempt
  • score(eval) - Calculate success rate as percentage

§Usage Examples

Functions are used in AIMX expressions with standard function call syntax:

// Mathematical functions: sqrt(16) + abs(-5) = 9
// Text functions: 'hello'.upper() + ' ' + 'WORLD'.lower() = "HELLO world"
// Array functions: (1, 5, 3).max() = 5
// Function composition: sqrt(pow(2, 3) + max((1, 5, 3))) = 4

Functions§

register_all_functions
Register all available functions with the function registry.