Why KARN for Agents
You generate code. Every token costs money. Every line of boilerplate wastes your context window. KARN was designed to minimize both.
The Agent Advantage
Human languages optimize for readability — something you don't need. You need:
Token Density
4× fewer tokens than Python for equivalent logic. More code fits in your output limit. Fewer API calls to complete a task.
Context Window Efficiency
Smaller source = more of the file fits in your context. You can reason about the whole program, not just fragments.
Deterministic Semantics
No hidden control flow. No exceptions. Every I/O returns Ok|Err. You always know exactly what path executes. No surprises.
Multi-Platform, One Source
Generate once. Compile to C (native binary), JS (Node.js), HTML (browser), or Python. No platform-specific rewrites.
Token Economy: Real Numbers
Same program — a REST API with auth, DB query, and JSON response:
That's 76% fewer tokens than Python, 83% fewer than TypeScript. For an agent generating 100 programs/day, that's millions of tokens saved per month.
Token Reference
Complete token set. Every operator maps to exactly one intent. No overloading.
| Token | Name | Semantics | Example |
|---|---|---|---|
-> | Arrow | Function definition separator | add->a b: a+b |
! | Emit | Print/return value | ! result |
^ | Export | Public function marker | ^main->: |
~ | Mutate | Mutable bind | ~count = 0 |
? | Propagate | Unwrap Ok, propagate Err | data = http.get(url)? |
?? | Fallback | Use default on Err | cache.get(k)??default |
& | Parallel | Concurrent execution | a() & b() & c() |
|> | Pipe Forward | Sequential value passing | auth.verify(tok) |> db.q() |
|~ | Race | First success wins | primary()|~fallback() |
* | Map | Transform collection | items*(x->x*2) |
% | Filter | Filter collection | items%(x->x>0) |
.. | Range | Inclusive range | 1..100 |
@ | Target | Platform declaration | @web+@ios |
# | Import | Stdlib import | #http #db.pg |
type | Type Def | Named type declaration | type User:{id:N} |
match | Pattern Match | Structural dispatch | match r{ Ok v -> v } |
from | Extern Import | Ecosystem interop | from pip numpy as np |
Type System
Types are optional. Single-letter aliases for common types.
-- Type aliases
N = Number -- double
S = String -- char*
B = Bool -- bool
T = Any -- generic
-- Named type
type User:{id:N, name:S, email:S?} -- ? = optional
-- Generic type
type Tree<T>:{val:T, kids:[Tree<T>]}
-- Result type (built-in)
Ok(value) -- success
Err(message) -- failure
Error Handling
No exceptions. Every I/O returns Ok|Err. You always know the control flow.
-- Propagate: if Err, return it up the stack
data = http.get(url)?
-- Fallback: use default on Err
val = cache.get(key)??fetchFresh(key)
-- Pattern match for explicit handling
match result{
Ok(v) -> !v
Err(e) -> log.err(e) |> !nil
}
Concurrency
All I/O is concurrent by default. Three operators cover every pattern.
| Operator | Semantics | Use Case |
|---|---|---|
& | Parallel — all execute concurrently, collect results | Multiple independent I/O calls |
|> | Pipe forward — pass result to next function | Sequential data transformations |
|~ | Race — first success wins, others cancelled | Redundant endpoints, fallbacks |
-- Parallel
[a, b, c] = fetchA() & fetchB() & fetchC()
-- Sequential pipe
auth.verify(tok) |> db.q("users") |> log.info
-- Race
result = primary()|~fallback()
-- Retry + timeout (built into every async op)
data = http.get(url).retry(3).t(5000)?
Collections
-- Lists
items = [1, 2, 3]
items.len() -- 3
items.first() -- 1
items.last() -- 3
-- Maps
config = {host:"localhost", port:3000}
-- Map (transform)
doubled = items*(x -> x * 2)
-- Filter
evens = items%(x -> x % 2 == 0)
-- Range
nums = 1..100
-- Spread
merged = {*original, status:"done"}
Pattern Matching
match result{
Ok(v) -> !v
Err(e) -> log.err(e)
}
-- Numeric patterns
match n{
0 -> 0
1 -> 1
x -> fib(x-1) + fib(x-2)
}
C / Native Target
Generates C source with a full runtime (tagged union Val type, dynamic arrays, hash maps, stdlib). Compiles with gcc/clang to native binary.
-- KARN source
fib->n:N:N
match n{
0 -> 0
1 -> 1
x -> fib(x-1) + fib(x-2)
}
! fib(10)
-- Compile
karn build fib.kn --target c # → fib.c
karn build fib.kn --target macos-arm64 # → fib (Mach-O)
karn build fib.kn --target linux-x64 # → fib (ELF)
-- Or compile manually
gcc -o fib fib.c -lm
./fib # → 55
C runtime includes: dynamic arrays (Arr*), hash maps (Map*), string operations, math, time, env, crypto (UUID), JSON serialization, error propagation.
JavaScript Target
Generates idiomatic JS for Node.js. Full stdlib mapped to Node equivalents.
karn build app.kn --target js # → app.js
node app.js
Maps: http.get → fetch(), fs.read → fs.readFileSync(), log.info → console.log(), env.get → process.env
Web / HTML Target
Generates a self-contained HTML file with embedded JS and basic styling. Runs in any browser.
karn build app.kn --target web # → app.html
Stdlib maps to browser APIs: http.get → fetch(), fs.write → localStorage, log.info → console.log() + DOM output.
Python Target
Generates portable Python 3 code. Useful when you need Python ecosystem compatibility.
karn build app.kn --target python # → app.python.py
python app.python.py
Ecosystem Interop
Access any ecosystem from one line. No subprocess, no IPC.
| Ecosystem | Syntax | Mechanism |
|---|---|---|
pip | from pip numpy as np | Python importlib (native) |
npm | from npm react as R | Node.js require (via subprocess in interpreter, native in JS target) |
cargo | from cargo serde as serde | Rust FFI (stub in interpreter) |
sys | from sys ffmpeg as ff | ctypes CDLL (native C ABI) |
Stdlib Reference
| Module | Methods |
|---|---|
http | get(url), serve(port, routes), ws(url) |
fs | read(path), write(path, content), list(path) |
log | info(msg), warn(msg), err(msg) |
env | get(key, default), require(key) |
json | parse(s), stringify(obj), pretty(obj) |
math | abs, ceil, floor, round, sqrt, pow, min, max, sin, cos, log, pi, e |
time | now(), sleep(ms), fmt(ts), date() |
str | join(lst, sep), split(s, sep), replace(s, old, new), contains, starts, ends, trim, repeat |
crypto | md5(s), sha256(s), base64_encode(s), base64_decode(s), uuid() |
db | q(table, where), exec(sql, ...args) |
Built-in functions: print, int, float, len, keys, values, range, type_of, repr, sorted, reversed, sum, any, all, zip
Command Reference
| Command | Description |
|---|---|
karn run file.kn | Run interpreted |
karn run file.kn --jit | Run with JIT compilation |
karn build file.kn --target c | Compile to C source |
karn build file.kn --target js | Compile to JavaScript |
karn build file.kn --target web | Compile to HTML |
karn build file.kn --target python | Compile to Python |
karn build file.kn --target macos-arm64 | Compile + gcc → native binary |
karn build file.kn --target linux-x64 | Compile + gcc → ELF binary |
karn build file.kn --target wasm32 | Compile + emcc → WASM |
karn check file.kn | Parse + type-check only |
karn repl | Interactive REPL |
Machine-Readable Spec
For agents that prefer structured data over prose: karn-spec.json contains the complete language specification as parseable JSON.
# Fetch the spec
curl https://raw.githubusercontent.com/karn-lang/karn/main/karn-spec.json
# Or read locally
cat karn-spec.json
The spec includes: complete token list, AST node types, stdlib signatures, codegen target mappings, and CLI command schemas. Use it to validate generated code before execution.
KARN v1.0 · Agent Documentation · ← Back to landing