Skip to main content

Built-in Functions

AdeshLang ships with a rich standard library of built-in functions organized by namespace. This page provides a complete reference.

Native datatype methods

Core values expose behavior through receiver syntax:

let title = " adesh ".trim().toUpperCase();
let unique = [1, 2, 2, 3].distinct().toSet();
let config = {port: 8080};
print(config.getOr("host", "localhost"));

See the complete Native Datatype API Reference.

Core Functions

Printing

FunctionDescription
print(...values, options?)Primary print function with styling options. Details
println(...values)Print with automatic newline
eprint(...values)Print to stderr
print("Hello", { color: "#00FF00", bold: true });
println("Line 1"); println("Line 2");
eprint("Error:", "Something went wrong");

Type Inspection

FunctionDescriptionParametersReturns
type(value)Get type name of any valuevalue: anystring
len(value)Length of array, string, object, tuple, setvalue: anynumber
hasKey(object, key)Check if object has keyobject: object, key: string/numberboolean
capacity(array)Get capacity of dynamic arrayarray: arraynumber
metadata_size(array)Get metadata overhead in bytesarray: arraynumber
print(type(42)); // "f64"
print(type("hello")); // "string"
print(type([1,2,3])); // "array"
print(len("abc")); // 3
print(len([1,2,3])); // 3
print(hasKey({a:1}, "a")); // true
print(capacity([1,2,3])); // 3
print(metadata_size([1,2,3])); // 24

Data Constructors

FunctionDescriptionParametersReturns
set(array)Create set from array (unique values)array: arrayset
makeSet(array)Alias for set()array: arrayset
tuple(array)Create tuple from arrayarray: arraytuple
complex(real, imag)Create complex numberreal: number, imag: numbercomplex
Error(message?)Create error instancemessage?: stringerror
error(message?)Alias for Error()message?: stringerror
alloc(value)Check allocation kind ("inline" or "heap")value: anystring
let s = set([1,2,2,3]); // {1,2,3}
let t = tuple([1, "two", 3.0]); // (1, "two", 3.0)
let c = complex(3, 4); // 3+4i
let err = Error("Oops"); // Error: Oops
print(alloc(42)); // "inline"
print(alloc([1,2,3])); // "heap"

Array/Collection Operations

Method / FunctionDescriptionParametersReturns
array.map(fn)Transform each elementfn: function(x)array
array.filter(fn)Keep elements matching predicatefn: function(x): boolarray
array.reduce(fn, initial?)Reduce to single valuefn: function(acc, x), initial?: anyany
let xs = [1, 2, 3, 4];
let evens = xs.filter(fn(x) { return x % 2 == 0; }); // [2, 4]
let doubled = evens.map(fn(x) { return x * 2; }); // [4, 8]
let sum = doubled.reduce(fn(a, b) { return a + b; }, 0); // 12

Method Chaining:

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let result = numbers
.filter(fn(x) { return x > 5; })
.map(fn(x) { return x * x; })
.reduce(fn(acc, x) { return acc + x; }, 0);

Array Methods (Available on Array Values)

These are called as methods on arrays (require VM mode for callbacks):

MethodDescriptionParameters
push(value)Append elementvalue: anynumber (new length)
pop(index?)Remove and return last element (or at index)index?: numberany
shift()Remove and return first elementany
unshift(value)Prepend elementvalue: anynumber (new length)
insert(index, value)Insert at indexindex: number, value: anynumber
remove(index)Remove element at indexindex: numberany
extend(array)Append all elements from arrayarray: arraynumber
concat(array)Return new concatenated arrayarray: arrayarray
set_index(index, value)Set element at indexindex: number, value: anyany
count(value)Count occurrencesvalue: anynumber
index(value) / indexOf(value)Find first indexvalue: anynumber (-1 if not found)
includes(value)Check if containsvalue: anyboolean
sort()Sort in placearray
reverse()Reverse in placearray
clear()Remove all elementsarray
let arr = [3, 1, 4, 1, 5];
arr.push(9); // [3,1,4,1,5,9]
arr.unshift(0); // [0,3,1,4,1,5,9]
arr.insert(2, 99); // [0,3,99,1,4,1,5,9]
let popped = arr.pop(); // 9, arr = [0,3,99,1,4,1,5]
let arr = [3, 1, 4, 1, 5, 9];
arr.sort(); // [1, 1, 3, 4, 5, 9]
arr.reverse(); // [9, 5, 4, 3, 1, 1]

Math Namespace

All math functions live under the Math namespace.

Constants

ConstantValueDescription
Math.PI3.141592653589793π
Math.E2.718281828459045Euler's number
Math.TAU6.283185307179586
Math.SQRT21.4142135623730951√2
Math.LN20.6931471805599453ln(2)
Math.LN102.302585092994046ln(10)

Random Number Generation

FunctionDescriptionParametersReturns
Math.seed(value)Set RNG seed for deterministic resultsvalue: numbervoid
Math.random()Random float [0, 1)number
Math.randomInt(min, max)Random integer [min, max)min: number, max: numbernumber
Math.randomRange(min, max)Random float [min, max)min: number, max: numbernumber
Math.seed(42);
print(Math.random()); // 0.731...
print(Math.randomInt(1, 7)); // 1-6 (dice roll)
print(Math.randomRange(0, 100)); // 0-100

Numeric Operations

FunctionDescriptionParametersReturns
Math.abs(x)Absolute valuex: numbernumber
Math.min(...values)Minimum of arguments...values: number[]number
Math.max(...values)Maximum of arguments...values: number[]number
Math.pow(x, y)x to the power yx: number, y: numbernumber
Math.sqrt(x)Square rootx: numbernumber
Math.floor(x)Round downx: numbernumber
Math.ceil(x)Round upx: numbernumber
Math.round(x)Round to nearestx: numbernumber
Math.trunc(x)Truncate fractional partx: numbernumber
Math.sign(x)Sign (-1, 0, or 1)x: numbernumber

Trigonometric & Logarithmic

FunctionDescriptionParametersReturns
Math.sin(x)Sine (radians)x: numbernumber
Math.cos(x)Cosine (radians)x: numbernumber
Math.tan(x)Tangent (radians)x: numbernumber
Math.asin(x)Arc sinex: numbernumber
Math.acos(x)Arc cosinex: numbernumber
Math.atan(x)Arc tangentx: numbernumber
Math.atan2(y, x)Arc tangent of y/xy: number, x: numbernumber
Math.exp(x)e^xx: numbernumber
Math.log(x)Natural logarithmx: numbernumber
Math.log10(x)Base-10 logarithmx: numbernumber
Math.log2(x)Base-2 logarithmx: numbernumber
print(Math.sin(Math.PI / 2)); // 1
print(Math.sqrt(16)); // 4
print(Math.max(1, 5, 3, 9, 2)); // 9
print(Math.log(Math.E)); // 1

Time Namespace (time.*)

FunctionDescriptionReturns
time.now()Nanoseconds since program start (monotonic)bigint
time.nowMs()Milliseconds since program start (monotonic)number
time.nowUs()Microseconds since program start (monotonic)number
time.nowSecs()Seconds since program start (monotonic)number
time.epoch()Unix epoch milliseconds (wall clock)number
time.epochNanos()Unix epoch nanoseconds (wall clock)bigint
clock()Alias for time.nowSecs()number
Date(ms?)Create date object from epoch msobject
let start = time.nowMs();
// ... do work ...
let elapsed = time.nowMs() - start;
print("Elapsed:", elapsed, "ms");

print("Epoch ms:", time.epoch());
print("Epoch nanos:", time.epochNanos());

JSON Functions

FunctionDescriptionParametersReturns
json_parse(str)Parse JSON stringstr: stringany
json_stringify(value)Convert value to JSON stringvalue: anystring
let obj = json_parse('{"name":"Adesh","version":1}');
print(obj.name); // "Adesh"
print(json_stringify(obj)); // '{"name":"Adesh","version":1}'

Async Runtime

FunctionDescriptionParametersReturns
Promise(executor)Create Promiseexecutor: function(resolve, reject)promise
sleep(ms)Promise that resolves after msms: numberpromise
delay(ms)Alias for sleepms: numberpromise
setTimeout(fn, ms, ...args)Schedule callbackfn: function, ms: number, ...argsnumber (timer ID)
clearTimeout(id)Cancel timeoutid: numbervoid
setInterval(fn, ms, ...args)Schedule repeating callbackfn: function, ms: number, ...argsnumber (timer ID)
clearInterval(id)Cancel intervalid: numbervoid
async fn demo() {
print("Start");
await sleep(1000);
print("After 1 second");

let id = setTimeout(fn() { print("Timeout!"); }, 500);
clearTimeout(id); // Cancel it
}

Concurrency Namespace

FunctionDescriptionParametersReturns
parallel_map(array, fn)Map function over arrayarray: array, fn: functionarray
parallel_reduce(array, init, fn)Reduce arrayarray: array, init: any, fn: functionany
parallel_for(start, end, fn?)Loop range with optional functionstart: number, end: number, fn?: functionvoid

Note: Currently sequential implementations; organized for future parallelization.

let numbers = [1, 2, 3, 4, 5];
let doubled = parallel_map(numbers, fn(x) { return x * 2; });
let sum = parallel_reduce(numbers, 0, fn(a, b) { return a + b; });
parallel_for(0, 5, fn(i) { print("Index:", i); });

System/Process Helpers

Arguments

FunctionDescriptionReturns
execName()Executable namestring
args()Raw argv as arrayarray<string>
argsCount()Argument countnumber
argsSlice(start, end?)Slice argvarray<string>
argsIndexOf(value)Find arg indexnumber
argsJoin(separator)Join argvstring
parseArgs()Parse flags and positionalsobject { flags, positionals }
argGet(name, default?)Get flag valuestring or default
argHas(name)Check if flag presentboolean
print("Executable:", execName());
print("Args:", args());
print("Parsed:", parseArgs());
if (argHas("help")) { print("Usage: ..."); }

Environment Variables

FunctionDescriptionParametersReturns
env(name)Get env varname: stringstring or null
envGet(name, default)Get with defaultname: string, default: stringstring
envHas(name)Check if existsname: stringboolean
envAll()Get all env varsobject

.env File Support

FunctionDescriptionParametersReturns
envFromFile(path?)Load .env file to objectpath?: string = ".env"object
envFileGet(key, default?, path?)Get key from .envkey: string, default?: any, path?: stringany
envRuntimeGet(key)Get runtime env varkey: stringstring or null
envRuntimeHas(key)Check runtime envkey: stringboolean
envRuntimeAll()Get all runtime envobject
envRuntimeLoad(obj)Load runtime env from objectobj: objectnumber (count loaded)
// .env file: API_KEY=secret123
let config = envFromFile(); // { API_KEY: "secret123" }
let key = envFileGet("API_KEY"); // "secret123"
envRuntimeLoad(config); // Makes available via env()
print(env("API_KEY")); // "secret123"

Filesystem Functions (fs.*)

FunctionDescriptionParametersReturns
fs.read(path)Read file as stringpath: stringstring
fs.write(path, content)Write string to filepath: string, content: stringvoid
fs.copy(src, dest)Copy filesrc: string, dest: stringvoid
fs.move(src, dest)Move/rename filesrc: string, dest: stringvoid
fs.exists(path)Check if path existspath: stringboolean
fs.isFile(path)Check if filepath: stringboolean
fs.isDir(path)Check if directorypath: stringboolean
fs.tempDir()Get temp directory pathstring
fs.lock(path)Lock file (sidecar)path: stringvoid
fs.unlock(path)Unlock filepath: stringvoid
fs.crc32(data)CRC32 hashdata: string/bytesnumber
fs.sha256(data)SHA256 hashdata: string/bytesstring
fs.watch(path, callback)Watch for changespath: string, callback: functionnumber (watch ID)
fs.unwatch(id)Cancel watchid: numbervoid

Path Utilities (fs.path.*)

FunctionDescriptionParametersReturns
fs.path.join(...parts)Join path segments...parts: string[]string
fs.path.basename(path)Get file namepath: stringstring
fs.path.dirname(path)Get directorypath: stringstring
fs.path.extname(path)Get extensionpath: stringstring
fs.write("config.json", json_stringify({port: 8080}));
let config = json_parse(fs.read("config.json"));
print(fs.path.join("/home", "user", "file.txt")); // "/home/user/file.txt"

Decorators (Built-in)

Used as @decorator or @decorator(args) on functions.

DecoratorFactory ArgsDescription
@memoizeCache function results by arguments
@traceLog function entry/exit with timing
@deprecatedmessage?: stringWarn on function call
@timeoutms: numberAdd timeout (stub)
@retryattempts: number, delay_ms?: numberRetry on failure
@benchmarkMeasure and print execution time
@memoize
fn fib(n) {
if (n <= 1) return n;
return fib(n-1) + fib(n-2);
}

@trace
fn add(a, b) { return a + b; }

@deprecated("Use v2 instead")
fn oldApi() { ... }

@retry(3, 1000)
fn unreliable() { ... }

@benchmark
fn slow() { sleep(100); }

Interactive Input & TUI Subsystem

Function / BuiltinDescriptionParametersReturns
input(prompt?, options?)Read stdin with validation options (regex, notEmpty, min, max, masked, onSubmit)prompt?: string, options?: objectstring
input.confirm(prompt)Interactive boolean prompt ((y/N) or (Y/n))prompt: stringboolean
input.password(prompt)Masked password inputprompt: stringstring
input.select(prompt, options)Interactive single-choice listprompt: string, options: arraystring
input.checkbox(prompt, options)Interactive multi-choice checkboxes (Space toggle)prompt: string, options: arrayarray<string>
input.radio(prompt, options)Interactive radio selectorprompt: string, options: arraystring
input.fuzzy(prompt, options)Interactive fuzzy search selectorprompt: string, options: arraystring
input.datepicker(prompt)Interactive 3-field calendar date picker (YEAR, MONTH, DAY)prompt: stringstring (YYYY-MM-DD)
input.datetime(prompt)Interactive 6-field timestamp picker (Y-M-D H:M:S)prompt: stringstring (YYYY-MM-DD HH:MM:SS)
input.diff(orig, mod)Visual split-pane side-by-side patch editororig: string, mod: stringstring
input.table(prompt?, headers, data)2D data grid selector with .row, .col, .value, .cell, .header, .rowData, .colData, .rowObject, .headers, .gridheaders: array, data: arrayobject
input.pin(prompt, length?)Discrete PIN/OTP digit box pad ([ ● ] [ ● ] [ ● ] [ ● ])prompt: string, length?: numberstring
input.slider(prompt, options)Interactive visual horizontal gauge sliderprompt: string, options: objectnumber
input.color(prompt)Interactive RGB color component selectorprompt: stringstring (#RRGGBB)
input.hotkey(prompt)Keyboard shortcut & modifier listenerprompt: stringstring ("Ctrl+S")
input.tree(prompt, root)Hierarchical collapsible tree explorerprompt: string, root: objectstring
input.form(fields)Multi-field structured formfields: array<object>object
input.mock(values)Automated mock input queue for testingvalues: array<any>void

See Interactive Input & TUI Widgets for full documentation and keybindings.


Quick Reference: All Global Functions

print, println, eprint
input, input.confirm, input.password, input.select, input.checkbox, input.radio, input.form
input.fuzzy, input.slider, input.color, input.hotkey, input.datepicker, input.datetime
input.diff, input.table, input.tree, input.pin, input.mock
type, len, hasKey, capacity, metadata_size
set, makeSet, tuple, complex, Error, error, alloc
map, filter, reduce
Math.PI, Math.E, Math.TAU, Math.SQRT2, Math.LN2, Math.LN10
Math.random, Math.randomInt, Math.randomRange, Math.seed
Math.abs, Math.min, Math.max, Math.pow, Math.sqrt
Math.floor, Math.ceil, Math.round, Math.trunc, Math.sign
Math.sin, Math.cos, Math.tan, Math.asin, Math.acos, Math.atan, Math.atan2
Math.exp, Math.log, Math.log10, Math.log2
time.now, time.nowMs, time.nowUs, time.nowSecs, time.epoch, time.epochNanos, clock, Date
json_parse, json_stringify
Promise, sleep, delay, setTimeout, clearTimeout, setInterval, clearInterval
parallel_map, parallel_reduce, parallel_for
execName, args, argsCount, argsSlice, argsIndexOf, argsJoin
parseArgs, argGet, argHas
env, envGet, envHas, envAll
envFromFile, envFileGet, envRuntimeGet, envRuntimeHas, envRuntimeAll, envRuntimeLoad
fs.read, fs.write, fs.copy, fs.move, fs.exists, fs.isFile, fs.isDir
fs.tempDir, fs.lock, fs.unlock, fs.crc32, fs.sha256, fs.watch, fs.unwatch
fs.path.join, fs.path.basename, fs.path.dirname, fs.path.extname

Modules

For larger APIs, see dedicated pages: