Skip to content

Arc Cheat Sheet ⚡

Comments

arc
# hash comment
// double-slash comment

Variables

arc
let x = 42              # immutable
let mut y = 0           # mutable
y = y + 1               # reassign mutable

Types

arc
let n = 42              # int
let f = 3.14            # float
let s = "hello"         # string
let b = true            # bool
let l = [1, 2, 3]       # list
let m = {a: 1, b: 2}    # map
let nothing = nil        # nil

Type Declarations

arc
# Named types — give meaning to primitives
type Email = String matching /^[^@]+@[^@]+$/
type Positive = Number where x > 0
type Age = Number where x >= 0 and x <= 150
type Username = String matching /^[a-zA-Z_]\w{2,19}$/

# Composite types
type User = {name: String, age: Age, email: Email}

# Union types
type Status = "active" | "inactive" | "banned"

Arc's type system is declaration-based, not annotation-based — by design. Instead of cluttering every function signature with types, you declare meaningful types once and the checker validates your code. Less ceremony, more meaning. Type declarations are checked at compile time via arc check file.arc — they are not runtime constructors (you don't call Email("foo@bar.com")).

Optional Chaining

arc
let user = {name: "Roger", address: {city: "NYC"}}
print(user?.name)                # "Roger"
print(user?.phone?.number)       # nil (no error)
print(user?.address?.city)       # "NYC"

Safe navigation through nested data — returns nil instead of crashing if any part is missing.

Strings

arc
let name = "world"
let greeting = "hello {name}"           # interpolation
let msg = "total: {x + y}"              # expressions work too
let info = "len: {len(items)}"          # function calls in interpolation
let first = "first: {items[0]}"         # indexing in interpolation
let multi = "line one
line two"                                # multiline
let repeated = "ha" * 3                  # "hahaha"

Functions

arc
fn add(a, b) { a + b }                  # implicit return (last expr)
fn greet(name) { return "hi {name}" }   # explicit return also works

# Default parameters
fn greet(name, greeting = "hello") { "{greeting} {name}" }

# Rest parameters
fn sum(...nums) { reduce(nums, (a, b) => a + b, 0) }

# Lambdas
let double = (x) => x * 2
let add = (a, b) => a + b

Control Flow

arc
# If/else (`else` or `el` — both work)
let result = if x > 0 { "positive" } else { "non-positive" }

# Match (pattern matching)
let msg = match status {
  200 => "ok",
  404 => "not found",
  400..499 => "client error",
  500..599 => "server error",
  _ => "unknown"
}

# For loops
for i in 0..5 { print(i) }
for item in list { print(item) }
for [key, val] in entries(map) { print("{key}: {val}") }

# While loops
while x < 10 { x = x + 1 }
while true {
  if done { break }
  continue
}

# Do-while / do-until
do { x = x + 1 } while x < 10
do { x = x + 1 } until x >= 10

Operators

arc
# Arithmetic
+ - * / % **            # add, sub, mul, div, mod, power

# String
"hello" + " world"      # concatenation (++ also works)
"ha" * 3                # repetition → "hahaha"

# Comparison
== != < > <= >=

# Logical
and or not

# Pipeline
data |> filter(x => x > 0) |> map(x => x * 2) |> sum()

# Range
0..5                    # [0, 1, 2, 3, 4]

# Optional chaining
obj?.prop               # nil if obj is nil

Try/Catch

arc
# catch requires a variable name (e.g. `catch e`, `catch err`)
try {
  let x = int("not a number")
} catch e {
  print("Error: " + e)
}

Built-in Functions

I/O

FunctionDescriptionExample
print(...)Print valuesprint("hello", 42)

Type Conversion

FunctionDescriptionExample
int(v)Convert to int (throws on bad input)int("42")42
float(v)Convert to float (throws on bad input)float("3.14")3.14
str(v)Convert to stringstr(42)"42"
bool(v)Convert to boolbool(0)false
type_of(v)Get type nametype_of([])"list"

String Functions

FunctionDescriptionExample
len(s)Length (codepoints)len("🔥")1
trim(s)Strip whitespacetrim(" hi ")"hi"
upper(s)Uppercaseupper("hi")"HI"
lower(s)Lowercaselower("HI")"hi"
split(s, sep)Split stringsplit("a,b", ",")["a","b"]
join(list, sep)Join stringsjoin(["a","b"], ",")"a,b"
replace(s, old, new)Replace allreplace("hi", "h", "H")"Hi"
contains(s, sub)Contains substringcontains("hello", "ell")true
starts(s, pre)Starts withstarts("hello", "he")true
ends(s, suf)Ends withends("hello", "lo")true
repeat(s, n)Repeat stringrepeat("-", 40)"----..."
chars(s)Split to charschars("hi")["h","i"]
slice(s, start, end)Substringslice("hello", 1, 3)"el"
index_of(s, sub)Find indexindex_of("hello", "l")2
ord(s)Char to codeord("A")65
chr(n)Code to charchr(65)"A"
char_at(s, i)Char at indexchar_at("hi", 0)"h"

List Functions

FunctionDescriptionExample
len(list)Lengthlen([1,2,3])3
map(list, fn)Transform eachmap([1,2], x => x*2)[2,4]
filter(list, fn)Keep matchingfilter([1,2,3], x => x>1)[2,3]
reduce(list, fn, init)Fold leftreduce([1,2,3], (a,b) => a+b, 0)6
fold(list, init, fn)Fold (init first)fold([1,2,3], 0, (a,b) => a+b)6
find(list, fn)First matchfind([1,2,3], x => x>1)2
any(list, fn)Any match?any([1,2,3], x => x>2)true
all(list, fn)All match?all([1,2,3], x => x>0)true
sort(list)Sortsort([3,1,2])[1,2,3]
head(list)First elementhead([1,2,3])1
tail(list)All but firsttail([1,2,3])[2,3]
last(list)Last elementlast([1,2,3])3
reverse(list)Reversereverse([1,2,3])[3,2,1]
take(list, n)First ntake([1,2,3], 2)[1,2]
drop(list, n)Skip ndrop([1,2,3], 1)[2,3]
flat(list)Flatten nestedflat([[1],[2,3]])[1,2,3]
zip(a, b)Zip two listszip([1,2],["a","b"])[[1,"a"],[2,"b"]]
enumerate(list)Add indicesenumerate(["a","b"])[[0,"a"],[1,"b"]]
push(list, item)Append (new list)push([1,2], 3)[1,2,3]
concat(a, b)Concatenateconcat([1],[2])[1,2]
sum(list)Sum numberssum([1,2,3])6
range(a, b)Number rangerange(0, 5)[0,1,2,3,4]
contains(list, v)Has element?contains([1,2], 2)true

Map Functions

FunctionDescriptionExample
len(map)Number of keyslen({a:1, b:2})2
keys(map)Get keyskeys({a:1})["a"]
values(map)Get valuesvalues({a:1})[1]
entries(map)Key-value pairsentries({a:1})[{key:"a",value:1}]

Math

FunctionDescriptionExample
abs(n)Absolute valueabs(-5)5
min(a, b) / min(list)Minimummin(1, 2)1
max(a, b) / max(list)Maximummax(1, 2)2
round(n)Roundround(3.7)4

Other

FunctionDescriptionExample
assert(cond, msg)Assert truthassert(x > 0, "must be positive")
time_ms()Unix timestamp mstime_ms()1708000000000
to_string(v)Alias for strto_string(42)"42"

Modules (use)

arc
use math                 # import module
math.sqrt(16)            # namespace access
use math { sqrt, PI }    # selective import
sqrt(16)                 # direct access

Key Modules

ModuleHighlights
mathsqrt, pow, ceil, floor, clamp, PI, E, sin, cos, log
stringspad_left, pad_right, capitalize, words
collectionsgroup_by, chunk, flatten, zip_with, partition, sort_by, unique
mapmerge, map_values, filter_map, from_pairs, pick, omit
ioread_file, write_file, read_lines, exists, append
httpget, post, put, delete — real HTTP requests
jsonto_json, from_json, pretty, get_path
csvparse_csv, to_csv, parse_csv_headers
regexmatch, find, test, replace, split, capture
datetimenow, today, parse, format, add_days, diff_days
oscwd, list_dir, mkdir, exec, platform, env, remove, copy
envget, set, has, all — environment variables
cryptosha256, sha512, hmac_sha256, uuid, random_bytes
errortry_catch, try_finally, throw, retry, assert
resultok, err, is_ok, unwrap, map_result, try_fn
netws_connect, tcp_connect, dns_lookup, base64_encode
yamlparse, stringify
tomlparse, stringify
htmlparse, create_element, to_html
pathjoin, dirname, basename, extname
loginfo, warn, error, debug
storeget, set, delete — persistent key-value storage
testdescribe, it, expect_eq, run_tests

Toolchain

bash
arc run file.arc         # Run a program
arc repl                 # Interactive REPL
arc new myproject        # Scaffold a project
arc build                # Build a project
arc test dir/            # Run tests
arc fmt file.arc         # Format code
arc lint file.arc        # Lint code
arc check file.arc       # Type check
arc parse file.arc       # Show AST
arc ir file.arc          # Show IR
arc compile file.arc     # Compile to JS
arc builtins             # List all built-in functions

Agent Workflows

arc
// HTTP requests
use http
let res = http.get("https://api.example.com/data")
print(res.status)  // 200
print(res.data)    // response body (parsed JSON or string)
print(res.ok)      // true if 2xx

// Fetch (parallel HTTP)
let [weather, news] = fetch [
  @GET "https://api.weather.com/current",
  @GET "https://api.news.com/top"
]

// Environment variables
use env
let api_key = env.get("API_KEY")

// Shell commands
use os
let output = os.exec("ls -la")
print(output)

// File I/O
use io
let content = io.read_file("config.json")
io.write_file("output.txt", "hello")

// JSON processing
use json
let data = json.from_json(content)
let pretty = json.pretty(data)

// Error handling
try {
  let val = int(user_input)
} catch e {
  print("Invalid: " + e)
}

A programming language designed by AI agents, for AI agents.