aimx/functions/mod.rs
1//! Built-in function library for AIM expressions.
2//!
3//! This module provides a comprehensive collection of built-in functions organized by category
4//! to extend the capabilities of AIM expressions. Functions can be called directly as
5//! `function_name(args)` or as methods on values like `array.sum()`.
6//!
7//! # Overview
8//!
9//! The function library is designed to provide spreadsheet-like functionality with the power
10//! of a programming language. Functions are organized into logical categories and can be
11//! composed together to create complex expressions.
12//!
13//! # Function Categories
14//!
15//! The function library is organized into the following categories:
16//!
17//! ## Business Functions
18//! Financial calculations, growth analysis, and business metrics.
19//! - `round_to(number, decimals)` - Round with decimal control
20//! - `percent_of(number, total)` - Calculate percentage of total
21//! - `increase(number, percent)` - Increase by percentage
22//! - `decrease(number, percent)` - Decrease by percentage
23//! - `gross_margin(cost, price)` - Calculate gross margin
24//! - `markup(cost, percent)` - Apply markup to cost
25//! - `growth(from, to)` - Calculate period-over-period growth
26//! - `runway(funding, expenses)` - Calculate runway based on funding and expenses
27//! - `monthly_payment(principal, rate, years)` - Calculate monthly loan payment
28//! - `break_even(fixed_costs, price, variable_cost)` - Calculate break-even point
29//! - `roi(investment, return_amount)` - Calculate Return on Investment
30//! - `split_amount(percentages, total)` - Split amount across percentages
31//! - `tax_inclusive(amount, tax_rate)` - Calculate tax-inclusive amount
32//! - `tax_exclusive(amount, tax_rate)` - Calculate tax-exclusive amount
33//!
34//! ## Collection Functions
35//! Array manipulation, filtering, and transformation functions.
36//! - `len(array)` - Length of array or string
37//! - `count(array)` - Count of array elements
38//! - `find(array, closure)` - Returns the first element that satisfies a predicate
39//! - `find_index(array, closure)` - Returns the index of the first element that satisfies a predicate
40//! - `flatten(array)` - Flatten nested arrays
41//! - `unique(array)` - Get unique elements from single array
42//! - `reverse(array)` - Reverse array
43//! - `take(array, count)` - Get first n elements
44//! - `take_right(array, count)` - Get last n elements
45//! - `skip(array, count)` - Skip first n elements
46//! - `skip_right(array, count)` - Skip last n elements
47//! - `chunk(array, size)` - Chunk array into groups of n
48//! - `group_by(array, closure)` - Group elements by key from closure
49//! - `partition(array, closure)` - Partition array into two based on predicate
50//! - `sort_by(array, closure)` - Sort array by closure
51//! - `all_unique(array)` - Check if all elements are unique
52//! - `take_while(array, closure)` - Take elements while predicate is true
53//! - `skip_while(array, closure)` - Skip elements while predicate is true
54//! - `zip(array1, array2)` - Zip two arrays together into pairs
55//! - `unzip(pairs)` - Unzip array of pairs into two arrays
56//!
57//! ## Date Functions
58//! Date parsing, formatting, and calculation functions.
59//! - `as_date(text, format)` - Parse text as date
60//! - `format_date(date, format)` - Format date as text
61//! - `days_between(date1, date2)` - Calculate days between dates
62//! - `add_days(date, days)` - Add days to date
63//! - `workdays(date1, date2)` - Calculate workdays between dates
64//! - Date methods:
65//! - `date.year()` - Year component
66//! - `date.month()` - Month component
67//! - `date.day()` - Day component
68//! - `date.hour()` - Hour component
69//! - `date.minute()` - Minute component
70//! - `date.second()` - Second component
71//!
72//! ## Functional Programming Support
73//! Higher-order functions for functional programming patterns.
74//! - `map(array, closure)` - Apply closure to each element of array
75//! - `select(array, closure)` - Like map but also provides the index to the closure
76//! - `filter(array, closure)` - Filter array elements using predicate closure
77//! - `reduce(array, initial, closure)` - Reduce array to single value using accumulator closure
78//! - `scan(array, initial, closure)` - Like reduce but keeps intermediate results
79//! - `some(array, closure)` - Returns true if any element satisfies the predicate
80//! - `every(array, closure)` - Returns true if all elements satisfy the predicate
81//! - `none(array, closure)` - Returns true if no elements satisfy the predicate
82//! - `exactly_one(array, closure)` - Returns true if exactly one element satisfies the predicate
83//!
84//! ## Mathematical Functions
85//! Basic arithmetic, trigonometric, logarithmic, and advanced mathematical operations.
86//! - `abs(x)` - Absolute value
87//! - `sign(x)` - Sign of number
88//! - `floor(x)` - Floor function
89//! - `ceil(x)` - Ceiling function
90//! - `round(x)` - Round to nearest integer
91//! - `trunc(x)` - Truncate decimal places
92//! - `sqrt(x)` - Square root
93//! - `pow(base, exp)` - Power function
94//! - `exp(x)` - e^x
95//! - `ln(x)` - Natural logarithm
96//! - `log10(x)` - Base 10 logarithm
97//! - `log2(x)` - Base 2 logarithm
98//! - `sin(x)` - Sine function
99//! - `cos(x)` - Cosine function
100//! - `tan(x)` - Tangent function
101//! - `asin(x)` - Arc sine
102//! - `acos(x)` - Arc cosine
103//! - `atan(x)` - Arc tangent
104//! - `atan2(y, x)` - Arc tangent with two arguments
105//! - `sinh(x)` - Hyperbolic sine
106//! - `cosh(x)` - Hyperbolic cosine
107//! - `tanh(x)` - Hyperbolic tangent
108//! - `random()` - Random number between 0 and 1
109//! - `clamp(x, min, max)` - Constrain to range
110//! - `lerp(a, b, t)` - Linear interpolation
111//! - `gcd(a, b)` - Greatest common divisor
112//! - `lcm(a, b)` - Least common multiple
113//! - `is_nan(x)` - Check if NaN
114//! - `is_finite(x)` - Check if finite
115//! - `PI()` - Mathematical constant π
116//! - `E()` - Mathematical constant e
117//! - `NaN()` - Not-a-number value
118//!
119//! ## Number Functions
120//! Number formatting and conversion utilities.
121//! - `ordinal(number)` - Convert number to ordinal (1st, 2nd, etc.)
122//! - `format_currency(number, symbol)` - Format as currency
123//! - `format_number(number, decimals)` - Format with specified decimals
124//!
125//! ## Set Functions
126//! Set operations on arrays.
127//! - `union(array1, array2)` - Returns the union of two arrays (unique elements from both)
128//! - `intersection(array1, array2)` - Returns the intersection of two arrays (elements common to both)
129//! - `difference(array1, array2)` - Returns elements in first array that are not in second array
130//! - `exclusive(array1, array2)` - Elements in either array but not both
131//! - `is_subset(array1, array2)` - Check if first array is subset of second array
132//! - `set_equals(array1, array2)` - Check if arrays are equal as sets (ignoring order)
133//! - `overlaps(array1, array2)` - Check if arrays have any common elements
134//!
135//! ## Statistical Functions
136//! Descriptive statistics, trend analysis, and data processing.
137//! - `min(array)` - Minimum value in array
138//! - `max(array)` - Maximum value in array
139//! - `sum(array)` - Sum of array values
140//! - `average(array)` - Average of array values
141//! - `avg(array)` - Average of array values
142//! - `median(array)` - Median value
143//! - `mode(array)` - Mode value
144//! - `range(array)` - Range of values
145//! - `stdev(array)` - Standard deviation
146//! - `variance(array)` - Variance
147//! - `percentile(array, percentage)` - Percentile value
148//! - `quartile(array, quartile)` - Quartile value (1, 2, or 3)
149//! - `growth_rate(from, to)` - Growth rate calculation
150//! - `slope(x_values, y_values)` - Linear regression slope
151//! - `correlation(x_values, y_values)` - Pearson correlation coefficient
152//! - `moving_average(array, period)` - Moving average
153//! - `cumulative_sum(array)` - Cumulative sum array
154//! - `rank(array, value)` - Rank of value in array
155//! - `percentile_rank(array, value)` - Percentile rank of value
156//! - `outliers(array)` - Array of outlier values
157//! - `frequency(array, bins)` - Frequency distribution
158//! - `unique_count(array)` - Count of unique values
159//! - Various count functions:
160//! - `count_if_gt(array, threshold)` - Count values > threshold
161//! - `count_if_ge(array, threshold)` - Count values >= threshold
162//! - `count_if_lt(array, threshold)` - Count values < threshold
163//! - `count_if_le(array, threshold)` - Count values <= threshold
164//! - `count_if(array, value)` - Count values equal to value
165//! - `count_if_ne(array, value)` - Count values not equal to value
166//! - `confidence(alpha, stdev, size)` - Confidence interval
167//! - `margin_of_error(array, alpha)` - Margin of error
168//!
169//! ## Task Functions
170//! Task creation and management for agentic workflows.
171//! - `task(text)` - Create a new pending task with the text expression
172//! - `perform(tasks, attempts, closure)` - Perform pending tasks one by one with retry attempts
173//! - `follow(plan, closure)` - Like perform, but with entire plan (tasks).
174//! - Task methods:
175//! - `task.done()` - Mark task as completed
176//! - `task.pending()` - Mark task as pending
177//! - `task.failed()` - Mark task as failed
178//!
179//! ## Text Functions
180//! String manipulation, formatting, and analysis functions.
181//! - `concat(array)` - Concatenate array of strings
182//! - `join_with(array, sep)` - Join array with separator
183//! - `split(text, delim)` - Split text into array
184//! - `substring(text, start, len)` - Extract substring
185//! - `upper(text)` - Convert to uppercase
186//! - `lower(text)` - Convert to lowercase
187//! - `proper(text)` - Convert to proper case
188//! - `trim(text)` - Trim whitespace
189//! - `contains(text, sub)` - Check if contains substring
190//! - `replace(text, old, new)` - Replace first occurrence
191//! - `replace_all(text, old, new)` - Replace all occurrences
192//! - `starts_with(text, prefix)` - Check if starts with prefix
193//! - `ends_with(text, suffix)` - Check if ends with suffix
194//! - `if_empty(text, default)` - Return default if empty
195//! - `pluralize(text, count, suffix)` - Pluralize text
196//! - `truncate(text, len, suffix)` - Truncate text
197//! - `mask_sensitive(text, start, end)` - Mask sensitive data
198//!
199//! ## Miscellaneous Functions
200//! Debugging and development utilities.
201//! - `debug(value)` - Print value to stderr and return unchanged (useful for debugging expressions)
202//!
203//! ## Evaluation Functions
204//! Evaluation tracking and performance monitoring for agentic workflows.
205//! - `pass(eval)` - Record successful evaluation attempt
206//! - `fail(eval)` - Record failed evaluation attempt
207//! - `score(eval)` - Calculate success rate as percentage
208//!
209//! # Usage Examples
210//!
211//! Functions are used in AIMX expressions with standard function call syntax:
212//!
213//! ```aimx
214//! // Mathematical functions: sqrt(16) + abs(-5) = 9
215//! // Text functions: 'hello'.upper() + ' ' + 'WORLD'.lower() = "HELLO world"
216//! // Array functions: (1, 5, 3).max() = 5
217//! // Function composition: sqrt(pow(2, 3) + max((1, 5, 3))) = 4
218//! ```
219
220mod business;
221mod collection;
222mod date;
223mod eval;
224mod functional;
225mod math;
226mod misc;
227mod number;
228mod set;
229mod statistical;
230mod task;
231mod text;
232
233use crate::function_registry::FunctionRegistry;
234
235/// Register all available functions with the function registry.
236///
237/// This function registers all functions from all categories with the provided
238/// function registry, making them available for use in AIM expressions.
239///
240/// # Arguments
241///
242/// * `registry` - The function registry to populate with functions
243///
244/// In practice, these functions are automatically registered and made available for use in AIMX expressions.
245pub fn register_all_functions(registry: &mut FunctionRegistry) {
246 business::register_functions(registry);
247 collection::register_functions(registry);
248 date::register_functions(registry);
249 eval::register_functions(registry);
250 functional::register_functions(registry);
251 math::register_functions(registry);
252 misc::register_functions(registry);
253 number::register_functions(registry);
254 set::register_functions(registry);
255 statistical::register_functions(registry);
256 task::register_functions(registry);
257 text::register_functions(registry);
258 // Update list when you add new modules
259}