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 controlpercent_of(number, total)- Calculate percentage of totalincrease(number, percent)- Increase by percentagedecrease(number, percent)- Decrease by percentagegross_margin(cost, price)- Calculate gross marginmarkup(cost, percent)- Apply markup to costgrowth(from, to)- Calculate period-over-period growthrunway(funding, expenses)- Calculate runway based on funding and expensesmonthly_payment(principal, rate, years)- Calculate monthly loan paymentbreak_even(fixed_costs, price, variable_cost)- Calculate break-even pointroi(investment, return_amount)- Calculate Return on Investmentsplit_amount(percentages, total)- Split amount across percentagestax_inclusive(amount, tax_rate)- Calculate tax-inclusive amounttax_exclusive(amount, tax_rate)- Calculate tax-exclusive amount
§Collection Functions
Array manipulation, filtering, and transformation functions.
len(array)- Length of array or stringcount(array)- Count of array elementsfind(array, closure)- Returns the first element that satisfies a predicatefind_index(array, closure)- Returns the index of the first element that satisfies a predicateflatten(array)- Flatten nested arraysunique(array)- Get unique elements from single arrayreverse(array)- Reverse arraytake(array, count)- Get first n elementstake_right(array, count)- Get last n elementsskip(array, count)- Skip first n elementsskip_right(array, count)- Skip last n elementschunk(array, size)- Chunk array into groups of ngroup_by(array, closure)- Group elements by key from closurepartition(array, closure)- Partition array into two based on predicatesort_by(array, closure)- Sort array by closureall_unique(array)- Check if all elements are uniquetake_while(array, closure)- Take elements while predicate is trueskip_while(array, closure)- Skip elements while predicate is truezip(array1, array2)- Zip two arrays together into pairsunzip(pairs)- Unzip array of pairs into two arrays
§Date Functions
Date parsing, formatting, and calculation functions.
as_date(text, format)- Parse text as dateformat_date(date, format)- Format date as textdays_between(date1, date2)- Calculate days between datesadd_days(date, days)- Add days to dateworkdays(date1, date2)- Calculate workdays between dates- Date methods:
date.year()- Year componentdate.month()- Month componentdate.day()- Day componentdate.hour()- Hour componentdate.minute()- Minute componentdate.second()- Second component
§Functional Programming Support
Higher-order functions for functional programming patterns.
map(array, closure)- Apply closure to each element of arrayselect(array, closure)- Like map but also provides the index to the closurefilter(array, closure)- Filter array elements using predicate closurereduce(array, initial, closure)- Reduce array to single value using accumulator closurescan(array, initial, closure)- Like reduce but keeps intermediate resultssome(array, closure)- Returns true if any element satisfies the predicateevery(array, closure)- Returns true if all elements satisfy the predicatenone(array, closure)- Returns true if no elements satisfy the predicateexactly_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 valuesign(x)- Sign of numberfloor(x)- Floor functionceil(x)- Ceiling functionround(x)- Round to nearest integertrunc(x)- Truncate decimal placessqrt(x)- Square rootpow(base, exp)- Power functionexp(x)- e^xln(x)- Natural logarithmlog10(x)- Base 10 logarithmlog2(x)- Base 2 logarithmsin(x)- Sine functioncos(x)- Cosine functiontan(x)- Tangent functionasin(x)- Arc sineacos(x)- Arc cosineatan(x)- Arc tangentatan2(y, x)- Arc tangent with two argumentssinh(x)- Hyperbolic sinecosh(x)- Hyperbolic cosinetanh(x)- Hyperbolic tangentrandom()- Random number between 0 and 1clamp(x, min, max)- Constrain to rangelerp(a, b, t)- Linear interpolationgcd(a, b)- Greatest common divisorlcm(a, b)- Least common multipleis_nan(x)- Check if NaNis_finite(x)- Check if finitePI()- Mathematical constant πE()- Mathematical constant eNaN()- 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 currencyformat_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 arrayexclusive(array1, array2)- Elements in either array but not bothis_subset(array1, array2)- Check if first array is subset of second arrayset_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 arraymax(array)- Maximum value in arraysum(array)- Sum of array valuesaverage(array)- Average of array valuesavg(array)- Average of array valuesmedian(array)- Median valuemode(array)- Mode valuerange(array)- Range of valuesstdev(array)- Standard deviationvariance(array)- Variancepercentile(array, percentage)- Percentile valuequartile(array, quartile)- Quartile value (1, 2, or 3)growth_rate(from, to)- Growth rate calculationslope(x_values, y_values)- Linear regression slopecorrelation(x_values, y_values)- Pearson correlation coefficientmoving_average(array, period)- Moving averagecumulative_sum(array)- Cumulative sum arrayrank(array, value)- Rank of value in arraypercentile_rank(array, value)- Percentile rank of valueoutliers(array)- Array of outlier valuesfrequency(array, bins)- Frequency distributionunique_count(array)- Count of unique values- Various count functions:
count_if_gt(array, threshold)- Count values > thresholdcount_if_ge(array, threshold)- Count values >= thresholdcount_if_lt(array, threshold)- Count values < thresholdcount_if_le(array, threshold)- Count values <= thresholdcount_if(array, value)- Count values equal to valuecount_if_ne(array, value)- Count values not equal to value
confidence(alpha, stdev, size)- Confidence intervalmargin_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 expressionperform(tasks, attempts, closure)- Perform pending tasks one by one with retry attemptsfollow(plan, closure)- Like perform, but with entire plan (tasks).- Task methods:
task.done()- Mark task as completedtask.pending()- Mark task as pendingtask.failed()- Mark task as failed
§Text Functions
String manipulation, formatting, and analysis functions.
concat(array)- Concatenate array of stringsjoin_with(array, sep)- Join array with separatorsplit(text, delim)- Split text into arraysubstring(text, start, len)- Extract substringupper(text)- Convert to uppercaselower(text)- Convert to lowercaseproper(text)- Convert to proper casetrim(text)- Trim whitespacecontains(text, sub)- Check if contains substringreplace(text, old, new)- Replace first occurrencereplace_all(text, old, new)- Replace all occurrencesstarts_with(text, prefix)- Check if starts with prefixends_with(text, suffix)- Check if ends with suffixif_empty(text, default)- Return default if emptypluralize(text, count, suffix)- Pluralize texttruncate(text, len, suffix)- Truncate textmask_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 attemptfail(eval)- Record failed evaluation attemptscore(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))) = 4Functions§
- register_
all_ functions - Register all available functions with the function registry.