Grapa API Reference
For High-Level Grapa Programmers: This reference covers the functions and types you'll use most often when writing Grapa scripts and applications.
For Advanced Users: See the maintainer documentation for low-level functions, grammar development, and internal APIs.
Table of Contents
- Core Language
- Dynamic Code Execution
- Variables & Scope
- Data Structures
- Search & Analysis
- Control Flow
- Functional Programming
- Type & I/O
- Math Operations
- String Operations
- Array/Matrix Operations
- File System
- Time & Date
Core Language
Essential language constructs for writing Grapa scripts.
Comments
Grapa only supports block comments (/* ... */
). Line comments (// ...
) are not supported.
Comment Rules: - Outside {}
blocks: Comments can be at the end of lines - Inside {}
blocks: Comments must be on their own line - Class/function definitions: Comments must be on their own line
/* ✅ Correct */
x = 5; /* This works outside {} */
if (condition) {
/* This comment is correct */
x = 5;
}
/* ❌ Incorrect */
if (condition) {
x = 5; /* This will cause a syntax error */
}
Type System
Grapa uses dynamic typing with rich runtime type introspection. Everything in Grapa is data - functions, classes, primitives, and everything else are just different data types that can be manipulated, stored, and passed around.
.type()
- Get the type of an object (returns$STR
).str()
- Convert to string.int()
- Convert to integer.float()
- Convert to float.bool()
- Convert to boolean
/* Type checking */
if (value.type() == $INT) { ... }
if (value.type() == $STR) { ... }
if (value.type() == $ARRAY) { ... }
if (value.type() == $OP) { ... } /* Functions are data */
if (value.type() == $CLASS) { ... } /* Classes are data */
/* Type conversion */
text = number.str();
number = text.int();
/* Functions as data */
my_func = op(x) { x * 2; };
my_func.type().echo(); /* $OP */
Namespace System
Grapa has a dynamic namespace system managed by the execution tree:
$global
- Global namespace for persistent variables$local
- Local namespace (automatic for each function)- Automatic namespace creation for each execution context
- Hierarchical access to variables from parent namespaces
/* Global variables */
$global.config = {"debug": true};
/* Function with local namespace */
func = op(x) {
local_var = x * 2; /* In function's local namespace */
global_var = config; /* Access global namespace */
local_var.echo();
};
Basic Operations
.echo()
- Output text to console (method on strings/values).\n
- Exit console (in interactive mode)sleep(seconds)
- Pause execution
Comments
/* This is a block comment */
/* Line comments are not supported in Grapa */
Dynamic Code Execution
Grapa's most powerful feature is its ability to compile and execute code at runtime. This enables advanced meta-programming patterns.
Core Functions
op()(script)
- Compile string to executable function$sys().eval(script, params)
- Evaluate script with parameters$sys().compile(script)
- Pre-compile script for performance
Examples
/* Direct string execution */
op()("'Hello, World!'.echo();")();
/* Output: Hello, World! */
/* With parameters */
func = op("name"=0)("'Hello, ' + name + '!'.echo();");
func("Grapa");
/* Output: Hello, Grapa! */
/* System-level evaluation */
result = $sys().eval("x + y", {"x": 5, "y": 3});
result.echo(); /* 8 */
/* Compiled execution for performance */
compiled = $sys().compile("input * 2 + offset");
result = $sys().eval(compiled, {"input": 10, "offset": 5});
result.echo(); /* 25 */
/* Dynamic function generation */
operations = ["add", "sub", "mul"];
funcs = {};
i = 0;
while (i < operations.len()) {
op_name = operations.get(i);
code = "a " + op_name + " b";
funcs[op_name] = op("a"=0, "b"=0)(code);
i += 1;
}
/* Execute generated functions */
funcs["add"](5, 3).echo(); /* 8 */
funcs["mul"](5, 3).echo(); /* 15 */
Note: This is Grapa's core meta-programming capability, making it superior to most languages for dynamic code execution.
Variables & Scope
Variable declaration, assignment, and scope management.
Assignment
=
- Basic assignment+=
- Append to arraysglobal
- Declare global variablelocal
- Declare local variableconst
- Declare constant
Examples
name = "Grapa";
count = 42;
numbers = [1, 2, 3];
numbers += 4; /* Append to array */
Data Structures
Create and manipulate arrays, lists, and objects.
Array Operations
[item1, item2, ...]
- Create array+=
- Append to arraylen()
- Get array lengthsum()
- Sum array elementsmean()
- Calculate mean
List/Object Operations
{key: value, ...}
- Create list/object.key
- Access object property.keys()
- Get object keys.values()
- Get object values
Object Merging Operators
+=
- Append/nest second object within first++=
- Merge/flatten properties from both objects
Examples
/* Arrays */
numbers = [1, 2, 3, 4, 5];
numbers += 6;
total = numbers.sum();
average = numbers.mean();
/* Objects */
config = {"host": "localhost", "port": 8080};
host = config.host;
/* Object merging */
user = {"name": "John"};
profile = {"age": 30, "email": "john@example.com"};
/* Append (nested) */
user += profile;
user.echo(); /* {"name":"John",{"age":30,"email":"john@example.com"}} */
/* Merge (flattened) */
user = {"name": "John"};
user ++= profile;
user.echo(); /* {"name":"John","age":30,"email":"john@example.com"} */
Search & Analysis
Search, sort, and analyze data.
Search Functions
grep(pattern, options)
- Search text with regexsearch(data, pattern)
- Search in data structuresfindall(text, pattern)
- Find all matches
Analysis Functions
sort(data)
- Sort dataunique(data)
- Remove duplicatesgroup(data, key)
- Group data by key
Examples
text = "Hello world\nGoodbye world";
matches = text.grep("world", "o"); /* ["world", "world"] */
data = [3, 1, 4, 1, 5];
sorted_data = data.sort(); /* [1, 1, 3, 4, 5] */
unique_data = data.unique(); /* [3, 1, 4, 5] */
Control Flow
Control program execution and logic flow.
Conditionals
if (condition) {
/* code */
} else {
/* code */
}
Loops
/* While loop */
i = 0;
while (i < 5) {
("Iteration " + i.str()).echo();
i += 1;
};
/* For-loop equivalent with range and map */
(5).range(0,1).map(op(i) { ("Iteration " + i.str()).echo(); });
Functions
/* Define function */
my_function = op(a, b) {
a + b;
};
/* Call function */
result = my_function(10, 20);
Functional Programming
Parallel and sequential data processing functions.
Map, Filter, Reduce
map(data, function)
- Apply function to each element (parallel)filter(data, function)
- Filter elements (parallel)reduce(data, function, initial)
- Reduce to single value (sequential)
Examples
data = [1, 2, 3, 4, 5];
/* Map (parallel) */
doubled = data.map(op(x) { x * 2; });
/* Filter (parallel) */
evans = data.filter(op(x) { x % 2 == 0; });
/* Reduce (sequential) */
sum = data.reduce(op(acc, x) { acc + x; }, 0);
Note:
map
andfilter
are parallel by default and production-ready for high-throughput data processing.
Type & I/O
Type checking, conversion, and input/output operations.
Type Functions
type(value)
- Get type of valueint(value)
- Convert to integerfloat(value)
- Convert to floatstr(value)
- Convert to stringbool(value)
- Convert to boolean
I/O Functions
.echo()
- Output to console (method on strings/values)prompt(message)
- Get user input
Examples
value = "42";
number = int(value);
text = str(number);
name = prompt("Enter your name: ");
("Hello, " + name).echo();
Math Operations
Mathematical functions and operations.
Basic Math
+
,-
,*
,/
- Arithmetic operatorspow(base, exponent)
- Power functionabs(value)
- Absolute valuemod(value, divisor)
- Modulo operation
Constants
pi
- Pi constante
- Euler's number
Examples
result = 4 * 3;
power = pow(2, 10);
absolute = abs(-42);
remainder = mod(17, 5);
String Operations
String manipulation and analysis.
String Methods
.len()
- Get string length.upper()
- Convert to uppercase.lower()
- Convert to lowercase.trim([chars])
- Remove characters from both ends (default: space).ltrim([chars])
- Remove characters from left end (default: space).rtrim([chars])
- Remove characters from right end (default: space).split(delimiter)
- Split string.join(array)
- Join array into string.replace(old, new)
- Replace text.grep(pattern, options)
- Search with regex
Examples
text = " Hello, World! ";
length = text.len();
upper = text.trim().upper();
words = text.split(", ");
joined = words.join(" - ");
Array/Matrix Operations
Array and matrix manipulation.
Array Functions
shape(array)
- Get array dimensionsreshape(array, dimensions)
- Reshape arraysum(array)
- Sum elementsmean(array)
- Calculate mean
Matrix Functions
dot(matrix1, matrix2)
- Matrix multiplicationt(matrix)
- Transpose matrix
Examples
data = [1, 2, 3, 4, 5, 6];
matrix = reshape(data, [2, 3]);
transposed = t(matrix);
File System
File and directory operations.
File Operations
$file().get(path)
- Read file content$file().set(path, content)
- Write to file$file().ls(path)
- List directory contents$file().info(path)
- Get file information
Examples
/* Read file */
content = $file().get("data.txt").str();
/* Write file */
$file().set("output.txt", "Hello from Grapa!");
/* List files */
files = $file().ls(".");
for (file in files) {
("File: " + file.name).echo();
}
Time & Date
Time and date utilities.
Time Functions
$time()
- Get current timestamp$time().format(format)
- Format timestamp$time().add(seconds)
- Add time$time().sub(seconds)
- Subtract time
Examples
now = $time();
formatted = now.format("%Y-%m-%d %H:%M:%S");
tomorrow = now.add(86400); /* Add 24 hours */