Practical answers, design rationale, cross-language comparisons, and common gotchas for programmers coming from Python, JavaScript/TypeScript, Go, Rust, Java/C#, Lisp, Haskell/OCaml, Julia, SQL, and Prolog.
Looking for a compact syntax overview of every language feature? Read the Axioma Cheatsheet. For the full specification, see the Axioma Manual and HtDP in Axioma Textbook.
1. Construction, Types & the Object Model
Why Axioma does not
have the new keyword?
In languages like Java, C++, C#, JavaScript, Go, and Pascal,
new conflates five distinct operations
behind one special keyword: constructing records, instantiating domain
entities, building collections, allocating mutable heap cells, and
constructing error objects. Axioma separates each into an ordinary,
composable construct with no special keyword ceremony:
- Structs and algebraic data types (
data) generate first-class constructor functions. BecausePointandSomeare ordinary functions rather than syntax gated behindnew, you can call them directly, pass them to.map(...), pipe into them with|>, or compose them with>>:
type Point = struct { x :: Integer, y :: Integer }
p1: Point(3, 4)
p2: Point(x: 10, y: 20)
pts: [(1, 2), (5, 6)].map(pair => Point(pair[1], pair[2]))
expect p1.x + p2.y == 23
expect len(pts) == 2
- Ontological
Conceptentities use natural-language articles (a/an). Concepts are open-world F-logic / Description Logic classes rather than closed heap structs. Instantiating an individual reads like English and keeps ontological individuals distinct from plain data records:
concept Person
Person has name: ""
Person has age: 0
ada: a Person { name: "Ada", age: 36 }
grace: a Person with name: "Grace", age: 85
expect (ada is Person) and grace.name == "Grace"
- Built-in scalars and collections use rich literals and
lowercase constructor/conversion functions. TitleCase names
(
Integer,Array,Date,Money) stay pure first-class type/Concept values for annotations (::), membership (is), and reflection (sizeof(Int64)), while lowercase functions (integer("42"),array(),set(),dict(),stack(),money(5)) construct or convert values:
expect 42 is Integer
expect integer("42") == 42
expect array(1..3) == [1, 2, 3]
expect $5.00 == money(5)
- Mutable reference cells and type defaults separate places
(
ref) from values (make). Go'snew(T)allocates a zeroed pointer whilemake(T)initializes slices/maps — and inventing silent dummy "zeros" for types without a genuine identity (such asDateorEmail) manufactures quiet bugs. Axioma separates value defaults (make(T)/= default) from reference cells (ref(v),ref(T, v),&x):
n: make(Integer) # 0 (value)
cell: ref(Integer, 10) # *Integer reference cell
*cell = 25
expect n == 0 and *cell == 25
Errors are values constructed with
error(...)or raised directly. Instead ofthrow new Error("bad input"), writeerror("bad input")orraise "bad input"(writingthrow new ...produces a targeted syntax hint).newremains a free identifier. Functions and callers can freely name parameters and variablesnew(for example,replace(text, old, new)). Callingnew(...)as an undefined function emits a direct hint pointing toref(value),ref(Type, value), andref(make(Type)).
Why does
integer("42") work while Integer("42")
fails?
Axioma strictly separates types (TitleCase) from conversions/constructors (lowercase):
Integer,Float,String,Boolean,Int64,Array,Setare first-class type values used inx :: Integer,x is Integer,make(Integer), andsizeof(Int64). Calling a built-in type value likeInteger("42")raises an error.integer(x),int(x),int64(x),float(x),string(x)/str(x),boolean(x),array(x),set(x)are ordinary functions you can call and pass higher-order (["1", "2"].map(integer)).
nums: ["10", "20", "30"].map(integer)
expect nums == [10, 20, 30]
expect nums[1] is Integer
Why
does array() work with zero arguments, while
date(), email(), or boolean()
refuses?
A lowercase constructor accepts zero arguments if and only if its type has a genuine natural identity element (an empty container):
- Nullary allowed:
array()→[],set()→{},tuple()→(),dict()→{:},bytes()→b"",bag()→bag(),stack()→ emptyStack. - Nullary refused:
date(),time(),email(),url(),file(),pair(),integer(),boolean()require an input argument rather than inventing an arbitrary epoch (1970-01-01) or empty address that could flow silently into downstream logic. - Type-directed starting values: When generic or
declaration code genuinely wants a designated starting value for a type
(including
0forIntegerandfalseforBoolean), usemake(T)or= default, or inspect the full catalogue viatypes():
let count :: Integer = default
let flag :: Boolean = default
expect count == 0 and flag == false
expect make(Array) == [] and make(Boolean) == false
What
is the difference between concept, struct,
data, interface, and trait?
Programmers arriving from OOP (Java/C#/Python) or FP (Rust/Haskell/OCaml) often wonder which modeling tool to reach for:
| Construct | World assumption | Best for | Construction / Usage |
|---|---|---|---|
struct |
Closed product record | Fast, fixed-field value records | type Point = struct { x :: Integer, y :: Integer } →
Point(3, 4) |
data |
Closed sum type (ADT) | Tagged variants & exhaustive pattern matching | data Opt[T] = Some(v :: T) | Absent →
Some(5) |
concept |
Open-world frame + DL class | Domain ontologies, inheritance, automatic classification, KB rules | concept Person, ada: a Person { age: 36 },
Adult defines { ... } |
interface |
Open type-level contract | Polymorphic operations attached to any existing type
(struct, Integer, Concept) |
type Show = interface { render } +
implement Show for Point as { ... } |
trait |
Reusable method pack | Sharing methods across Concepts via uses
(not a type itself) |
trait Named { label: func() [ it.name ] } +
Person uses Named |
How
do methods refer to the current receiver — is there this or
self?
It depends on whether you are writing a Concept / trait method or an interface implementation:
- Inside
conceptactions andtraitmethods: Axioma binds the receiver automatically to the pronounit— do not add an extraselfparameter unless you intend a binary method! - Inside
implement Interface for Type as { ... }: Each operation is an explicit function whose first parameter receives the target value (func(p) [ ... ]).
trait Describable {
summary: func() [ f"{it.title} ({it.year})" ]
}
concept Book
Book uses Describable
Book has title: ""
Book has year: 0
b: a Book { title: "Organon", year: -350 }
expect b.summary() == "Organon (-350)"
What is the
difference between is, ==, ===,
and extends?
Following Bertrand Russell's analysis of the word "is", Axioma never overloads one operator for predication, inclusion, equality, and identity:
extendsdeclares subconcept inclusion:Dog extends Animal(statements that establish taxonomy; retired spellingsisaandkindofemit migration hints).isqueries membership or subsumption:5 is Integer(true),ada is Adult(true),Dog is Animal(true).==tests value equality across compatible representations:1 == 1.0(true),1/2 == 0.5(true),{1, 2} == {2, 1}(true), while cross-container comparisons like[1, 2] == (1, 2)arefalse.===(andsame?/identical?, negated!==) tests exact representation or reference identity:1 === 1.0isfalse(IntegervsFloat), and two distinct mutable arrays with equal elements satisfy[1] == [1](true) but[1] === [1](false).there isexpresses existential quantification:there is x in 1..10 | x > 8(true).
expect 1 == 1.0
expect not (1 === 1.0)
a: [1, 2]
b: [1, 2]
expect a == b and (a !== b) and (a === a)
Why
are A & B intersection types supported while negation
types (!T, not T, ¬T) are
refused?
- Intersection types (
A & BorA ⊓ B) hold whenever a value satisfies bothAandB, matchingv is (A ⊓ B). On structural schemas ({name :: String} & {age :: Integer}), fields merge cleanly; provably disjoint intersections likeInteger & Stringare rejected immediately at the annotation rather than creating an uninhabitedNevertrap. (Note:Float & 0..9is inhabited by whole floats like5.0!) - Negation types (
¬T,not T,!T) are intentionally refused in::slots because open-world Description Logic¬Concept("known not to beC") disagrees with closed complement typing ("any value exceptT"). To forbid specific values, attach acontract(requires:) or pattern guard:
type Named = { name :: String }
type Aged = { age :: Integer }
type PersonRec = Named & Aged
let p :: PersonRec = { name: "Ada", age: 36 }
safe_inv: func(x :: Number) :: Number [ 1 / x ]
contract safe_inv {
requires: x != 0
ensures: result * x == 1
}
expect p.name == "Ada" and safe_inv(4) == 1/4
Does
(Integer -> Integer) & (String -> String)
overload multiple function bodies?
No. An intersection of function arrows attaches to one
function body as a per-call contract: every arm whose parameter
types accept the call's arguments applies, and the body's single return
value must satisfy all applying arms' return types (calling with
2.5 fails as a caller type error because no arm accepts
Float). For multi-type open dispatch with separate
implementations per type, use interface +
implement + dispatch, or pattern-matched
clauses.
2. Bindings, Mutability & Scope
What is
the difference between :, =, :=,
let/val, var/local,
and const?
Axioma supports both concise scripting and strict mutability control:
| Form | Semantics | Mutability | Scope behavior |
|---|---|---|---|
x: 10 / x = 10 / x := 10 |
Find-or-update binding (all three are identical for values!) | Mutable | Updates existing x in scope (writes through in
blocks/loops); creates local x if absent |
f(x) = expr |
Function definition (parenthesized head makes = define
a function) |
Rebindable | Binds function f in current scope |
let x = 10 / val x = 10 |
Fresh immutable binding | Immutable | Always creates a fresh binding in the current scope (shadows outer
x); reassigning errors |
var x = 10 / local x = 10 /
let mut x = 10 |
Fresh mutable binding | Mutable | Always creates a fresh mutable binding in the current scope (shadows
outer x without clobbering it) |
const MAX = 100 |
Constant declaration | Immutable | Fixed constant binding |
let tax_rate = 0.08
var subtotal = 100
subtotal := subtotal + 25
total: subtotal * (1 + tax_rate)
expect total == 135.0
Why
did assigning inside a for/while loop update
my outer variable, while assigning inside func stayed
local?
This follows a deliberate ergonomic split (familiar from Julia and
Python, without Python's UnboundLocalError surprise in
loops):
- Loop and block bodies write through on bare
:,=,:=. Accumulators work naturally:total: 0outside afororwhileloop is updated bytotal: total + ninside the loop. Meanwhile, binder positions (for n in ..., comprehension generators,matchpattern variables, function parameters) always create a fresh local binding that shadows any outern. If you want a scratch variable inside a loop that never touches an outer variable of the same name, declare it withvar/local/let. - Named/anonymous functions isolate their locals by
default. Inside
func bump() { count: 99 },countis local tobumpso helper functions cannot accidentally clobber module-level state. Declareglobal countinside the function when you explicitly want to rebind a module global (mutating a shared collection in place viapush(items, x)already mutates the container withoutglobal).
sum_acc: 0
n: 999
for n in 1..4 {
sum_acc: sum_acc + n # writes through to outer sum_acc
}
expect sum_acc == 10
expect n == 999 # loop binder `n` shadowed outer `n`
counter: 0
func stay_local() { counter: 50 }
func touch_global() { global counter; counter: counter + 1 }
stay_local()
expect counter == 0
touch_global()
expect counter == 1
Why
can't I name a variable let, var,
val, or end — and how do I escape a reserved
word?
Words like let, var, val,
end, in, is,
concept, and relation are reserved lexer
tokens so binder and block errors are caught cleanly instead of falling
through to obscure runtime errors. Prefix any reserved
word with $ ($let,
$end, $in, $type) to use it as an
ordinary identifier, or quote keys in dictionaries
({"type": "event"}):
$type: "json"
$end: 100
expect $type == "json" and $end == 100
What
does a leading colon :name or leading single quote
'name do?
:name(REBOL get-word) fetches the value bound tonamewithout invoking zero-argument callables or forcing deferreddeclarebindings — handy when passing or inspecting definitions (g: :my_func,t: :deferred_val).'name(no closing quote —Wordliteral) produces a Lisp-style symbolic atom ('north,'ok) whose type isWord.'a'(with closing quote —Characterliteral) produces a single Unicode scalar value of typeCharacter(supportsc++/c--Unicode stepping!).
How
do declare, let/lazy, and
lazy val differ from lazy expr and
zero-argument functions?
Axioma separates call-by-need bindings, first-class promises, and recomputed formulas cleanly:
declare x = expr(also writtenlet/lazy,val/lazy,lazy val, orlazy let) creates a fresh, immutable, mutually recursive call-by-need binding (closest to Scala'slazy valplus GHC-style blackhole cycle detection, and distinct from Mozart/Oz's unbound dataflowdeclare Xor Swift's mutablelazy var). Readingxevaluatesexpronce, checks/converts any:: Typeannotation, and caches a successful result (failed reads are not cached and may retry).t = lazy (expr)creates an explicitThunkvalue (@t == Thunk) that stays inert when passed or stored in collections untilforce(t). For a mutable thunk handle, writevar t = lazy (expr).total() = 10 * rate(or Concepthas/computed) recomputes on every call whenever derived state should track later mutations.
var rate = 2
lazy val cached_total = 10 * rate
live_total() = 10 * rate
let/lazy left_v, right_v = right_v + 1, 41
rate = 3
expect cached_total == 30 and live_total() == 30 and left_v == 42
rate = 4
expect cached_total == 30 and live_total() == 40
sym: 'north
ch: 'A'
ch++
expect (sym is Word) and (ch is Character) and ch == 'B'
3. Containers, Indexing & Delimiters
Why
is {} the empty Set (∅) instead of an empty
Dictionary or an empty code block?
Axioma treats set theory as foundational rather than an afterthought imported from a library:
- In expression position,
{}is always the emptySet(∅, equal toset()),{1, 2, 3}is aSet,{a: 1, b: 2}is aDictionary, and{:}(ordict()) is the emptyDictionary. - In statement-body position (directly after
func(...),for ...,while ...,try,defer, or Go-styleif cond { ... }),{ ... }is a statement block! - Gotcha with
=equations: Inf() = { ... }, the right-hand side of=is an expression position, so{...}starts a Set or Dictionary literal (tags() = {"a", "b"}). For a multi-statement function body, writefunc f() { ... }orf() = [ ... ].
empty_set: {}
empty_dict: {:}
expect (empty_set is Set) and len(empty_set) == 0
expect (empty_dict is Dictionary) and len(empty_dict) == 0
Why
are Array, String, Tuple, and
Bytes 1-based instead of 0-based?
Like Julia, Mathematica, R, Lua, and standard mathematical notation
(a1, a2, …, an),
Axioma indexes sequences uniformly starting at
1, with inclusive slices
xs[2:4] and end-relative indices xs[-1] or
xs[$]:
xs: ["a", "b", "c", "d"]
expect xs[1] == "a"
expect xs[-1] == "d" and xs[$] == "d"
expect xs[2:3] == ["b", "c"]
var buf :: Slice of Uint8 = [10, 20, 30]
expect buf[0] == uint8(10)
When working with binary buffers or systems code that genuinely wants 0-based offsets, Axioma provides dedicated 0-based types:
Slice of T:var s :: Slice of Uint8 = [10, 20, 30](s[0]→uint8(10))- Declared index domains:
var a :: Array[0..<3] of Integer(indices(a)→[0, 1, 2])
Why
do [ ... ] brackets mean a statement block in
func(x) [ ... ], and how do I return a 1-element Array
[x]?
In Axioma (inheriting from REBOL and Pop-11):
- Body slots (
func(x) [ ... ],while cond [ ... ],for x in xs [ ... ]) read[ ... ]as a statement sequence. - Expression slots (
let a = [1, 2],if c then [1] else [2]) read[ ... ]as anArrayliteral.
Gotcha: Inside a bracket body
func wrap(x) [ [x] ], the inner [x] has no
comma, so it is parsed as a nested single-statement block evaluating to
x! To construct a 1-element Array
unambiguously in any position, either add a trailing
comma [x,] or use a braced function
body func wrap(x) { [x] }:
wrap_comma(x) = [ [x,] ]
func wrap_brace(x) { [x] }
expect wrap_comma(7) == [7] and wrap_brace(7) == [7]
What
is the difference between Array ([1, 2]),
List (`[1, 2]), Tuple
((1, 2)), and Set ({1, 2})?
| Container | Literal | Mutable? | Order & Duplicates | Key operations |
|---|---|---|---|---|
Array |
[1, 2, 3] |
Yes (or Readonly Array of T) |
Ordered, duplicates kept | xs[1], push(xs, 4), pop(xs),
xs :+ 4, .map(...) |
List |
`[1, 2, 3] |
Immutable cons-list | Ordered, duplicates kept | 0 +: xs, cons(0, xs),
head(xs), tail(xs) (refuses
push/pop!) |
Tuple |
(1, "ok") · 1-tuple (1,) |
Immutable fixed-arity | Ordered, heterogeneous | t[1], pattern destructuring
(a, b) = t |
Set |
{1, 2, 3} · empty {} |
Value semantics (add! mutates variable) |
Unordered value; deterministic canonical walk | A ∪ B, A ∩ B, A \ B,
x in A, A ⊆ B |
Array and List literals both expand a directly written range. For
example, `[1..10..2] contains the five odd integers from 1
through 9. To keep the range itself in a single slot, bind
r = 1..10..2 and write `[r].
Calling in-place mutators like push(lst, x) on a
`[...] List fails loudly with a teaching hint
pointing to cons / +: / :+ or
Array.
Why
did [1, 2] :+ [3, 4] produce [1, 2, [3, 4]],
why is + (not ++) concatenation, and why does
(1 + 2) +: xs need parentheses?
x +: xs(prepend) andxs :+ x(append) add one element without mutatingxs— so an array passed as the element stays nested ([1, 2] :+ [3, 4]→[1, 2, [3, 4]]).+concatenates sequences ([1, 2] + [3, 4]→[1, 2, 3, 4],"ab" + "cd"→"abcd"). Unlike Haskell or Elixir,++is solely the postfix increment statementi++(on numbers andCharacters), not sequence concatenation!- Precedence gotcha: Unlike OCaml/Haskell
::, Axioma's+:and:+sit in the multiplicativeconsband above+, so1 + 2 +: [3]would try1 + (2 +: [3]). Parenthesize arithmetic elements:(1 + 2) +: [3]→[3, 3].
expect (1 + 2) +: [4, 5] == [3, 4, 5]
expect [1, 2] :+ 3 == [1, 2, 3]
expect [1, 2] + [3, 4] == [1, 2, 3, 4]
Why
do (1..10)[2:4] and reverse(1..10) return a
Range instead of an Array?
Finite and open ranges (1..10, 1..<10,
1..10..2, 1..) are compact arithmetic
progressions. Slicing, reversing, and re-striding (.by(2))
stay lazy O(1) Range values rather than allocating an
intermediate array.
.startand.endreturn the written bounds ((1..<10).endis10)..firstand.lastreturn the actual visited elements ((1..<10).lastis9).- Wrap in
[1..10]or callarray(r)whenever you want a materializedArray:
r: 1..<10
expect r.end == 10 and r.last == 9
expect (1..10)[2:4] == 2..4
expect reverse(1..5) == 5..1
expect array(1..4) == [1, 2, 3, 4]
Do
Set iterations leak random hash-map order like Go or
Python?
Never. While Set equality is unordered
({3, 1, 2} == {1, 2, 3} is true), every
traversal, comprehension, reduction, and print uses a single
deterministic canonical order (numeric order for numbers,
lexicographic for text). Two runs on the same set always visit elements
in the exact same order.
4. Operators, Numbers & Strings
Why does
1 / 2 return 1/2 (Rational)
instead of 0.5 or 0?
Axioma implements a full exact numeric tower by default so mathematical identities hold without IEEE-754 rounding drift:
- Exact division (
/): Dividing twoIntegers produces a reduced arbitrary-precisionRational(1 / 2→1/2,6 / 3→2,1/3 + 1/6 + 1/2 == 1→true!). - Float division (
fdivor Float operand): Writefdiv(1, 2)or1.0 / 2when you want an IEEE-754Float(0.5). - Integer division (
div,trunc, andmod/%): Infix7 div 2floors toward −∞ (-7 div 2→-4);trunc(-7 / 2)truncates toward0(-3). - Exact
Money($0.10): Backed bybig.Ratand rounded only at display, so$0.10 + $0.20 == $0.30istrue(whereas0.1 + 0.2in binary floating point is0.30000000000000004).
expect 1/3 + 1/6 + 1/2 == 1
expect fdiv(1, 2) == 0.5
expect (-7 div 2) == -4 and trunc(-7 / 2) == -3
expect $0.10 + $0.20 == $0.30
What is
the difference between Integer and Int /
Int64?
Integer(integer(x)) is Axioma's default arbitrary-precision integer —2 ^ 256never silently overflows!Int,Int8..Int64,UInt..UInt64,Float32,Float64,Byte,Rune(int(x),int64(x),float64(x),byte(x),rune(x)) are fixed-width machine scalars for low-level binary formats, typed slices, and FFI boundaries.
Why is
2x a syntax error, and why doesn't 2 x
multiply?
Axioma has no implicit juxtaposition multiplication
— always write 2 * x. Inside
[ ... ] blocks and postfix stack expressions
([2, 3, +]), whitespace separates adjacent
items/statements, so 2 x in a block evaluates
2 (discarded) followed by x.
Literal-identifier adjacency with zero space (2x) is caught
specifically at parse time with a clear SyntaxError so math
typos never slip through.
x: 5
y: 2x
Why
does // start a comment instead of Python-style floor
division?
Axioma accepts both # and // for line
comments and /* ... */ for block comments so readers from
Python/Ruby/Julia and C/Go/Rust/JS feel at home. Floor division is
div (7 div 2 →
3). (Note: inside parentheses with no spaces,
(//) is the slash-reduction fold operator for
/, e.g. (//)(100, [2, 5]) →
10.)
What is the
difference between "...", f"...",
r"...", t"...", b"...",
'a', and 'word?
| Literal | Type | Behavior |
|---|---|---|
"hello\n" |
String |
Standard UTF-8 string with backslash escapes |
f"sum = {1 + 2}" |
String |
Interpolated format string ("sum = 3") |
r"\d+\s+" |
String |
Raw string — backslashes stay literal (ideal for
regex_*) |
t"Hi {user}" |
Template |
Structured template capturing fields safely (e.g.,
html.render(t"...") auto-escapes HTML!) |
b"\x41\x42" |
Bytes |
Immutable 1-based byte sequence (Slice of Uint8 is
0-based) |
'λ' |
Character |
Single Unicode code point |
'token |
Word |
Quoted symbolic identifier (no closing quote) |
name: "Ada"
pat: r"^\w+$"
expect f"Hi, {name}!" == "Hi, Ada!"
expect regex_match(name, pat) and (name =~ pat).match == "Ada"
expect len(b"ABC") == 3 and b"ABC"[1] == byte(65)
5. Functions, Pipelines & Control Flow
Why
are there multiple ways to write functions (f(x) = ...,
func, fn, =>,
->, &.)?
All function spellings compile to the exact same closure representation, letting mathematical equations, multi-line imperative procedures, and tiny collection callbacks each read naturally:
square(x) = x * x # mathematical equation
add: func(a, b) [ a + b ] # block function (`fn`, `fun`, `function` also work)
mul: (a, b) => a * b # arrow lambda (`->` also works)
inc: x -> x + 1 # single-parameter arrow lambda
users: [{name: "Ada"}, {name: "Alan"}]
names: users.map(&.name) # member-access lambda (`\.name` / `λ.name` too)
expect square(4) == 16 and add(2, 3) == 5 and mul(3, 4) == 12
expect inc(9) == 10 and names == ["Ada", "Alan"]
How
do dot broadcasting f.(xs), .map(f), pipes
|>, and (op/) folds differ?
- Dot broadcasting
f.(xs): Applies any unary function elementwise across collections, ranges, or nested arrays, and fuses connected dotted calls (inc.(double.(xs))runs in a single pass with no intermediate array!). - Receiver
.map(f)/.filter(p): Method-chaining style familiar from JS/Rust/Scala (xs.filter(x -> x > 1).map(double)). - Pipeline
x |> f: Threads a value left-to-right (xs |> sum) and acts as an explicit materialization boundary between fused stages. - Slash reduction
(op/)(seed, xs): Concise left fold ((+/)(0, [1, 2, 3])→6, or curriedtotal: (+/)(0)). Seed is always explicit so empty inputs never guess an identity.
double(x) = 2 * x
inc(x) = x + 1
xs: [1, 2, 3]
expect inc.(double.(xs)) == [3, 5, 7]
expect (xs.map(double) |> (+/)(0)) == 12
What
is the difference between match ... with,
case ... end, switch, and
cond?
match expr with | pat -> res ...: Expression-oriented structural pattern matching (destructuring ADTs, tuples, arrays, ranges, guardswhen/if). Like OCaml/F#,match ... withdoes not take a trailingend!case expr | pat => res ... end: Block-closed structural pattern matching when you want an explicitenddelimiter (e.g., nested inside another expression).switch expr { case v => ... default => ... }: Imperative C/Go-style value/condition switch with no accidental fallthrough (explicitfallthrough/next caseif desired).cond | c1 => e1 | c2 => e2 | else => e3: Multi-way boolean guard ladder (cleaner than deeply nestedelse if).
sign_label(n) = cond
| n < 0 => "negative"
| n == 0 => "zero"
| else => "positive"
describe_pair(p) = match p with
| (0, 0) -> "origin"
| (x, 0) -> f"x-axis({x})"
| (x, y) -> f"({x}, {y})"
expect sign_label(-3) == "negative" and describe_pair((5, 0)) == "x-axis(5)"
Does
Axioma have defer or Python/Go-style scoped cleanup
(with)?
Yes — three complementary cleanup tools:
defer [ ... ]/defer { ... }: Runs in LIFO order when the enclosing function Scope exits (whether normally or on error).defer/error [ ... ]: Runs only if the enclosing scope exits with an error (Zig-style rollback!).with name = resource [ ... ]: Deterministic lexical scope cleanup for closeable/disposable resources.
steps_log: []
func work(fail?) {
defer { push(steps_log, "always-cleanup") }
defer/error { push(steps_log, "rollback") }
if fail? { raise "abort" }
push(steps_log, "committed")
}
work(false)
_ : attempt(work(true))
expect steps_log == ["committed", "always-cleanup", "rollback", "always-cleanup"]
Is
main.ax or func main() treated specially?
No. Like Python and Julia, any .ax file executes
top-to-bottom directly (axioma report.ax).
func main() is never implicitly called, and
axioma.json is completely optional (used only when you want
axioma --project . to share project settings and entry
points).
6. Nulls, Unknowns, Truthiness & Errors
Why
does Axioma have both none and om
(Ω), plus Absent — and why is
om == none false?
Most languages collapse "there is nothing at this key" and
"we do not know the answer" into a single
null/None, losing critical epistemic
distinctions:
none(typeNone): Known absence — a total lookup found no entry, or a procedure returned no value.om/Ω(typeOm, from SETL & Kleene logic): Genuinely undetermined / unknown value.om == noneisfalsebecause "known to be absent" is not "unknown"!Absent(paired withSome(v)): The empty constructor of the typed algebraicOptiondata type (Noneis the type ofnone, soOptionusesAbsentrather than colliding withNone).- Retired spellings
Nullandnothingfail with migration hints pointing tonone/None.
expect (none is None) and (om is Om)
expect (om == none) == false
opt: Some(10)
empty_opt: Absent
expect (opt is Option) and (empty_opt is Option)
Why are empty
collections ([], {}, "",
dict()) truthy in if?
In Python or JavaScript, if xs: conflates "empty
list" with "None" — a classic bug source when
[] is a valid result and none means
"missing". In Axioma:
- Falsy:
false,none,om(Ω), and undesignated multi-valued truth values (⊥ᵇ,?ᵇ,?ᵏ, …). - Truthy: Everything else — including
0,"",[],{},{:}, andError! - Always test emptiness explicitly with
empty?(xs)orlen(xs) == 0:
xs: []
expect (if xs then "present" else "missing") == "present"
expect empty?(xs)
Why
is an Error value truthy, and how do errors work without
exceptions everywhere?
Inspired by REBOL and Rust/Go errors-as-values,
error("msg") (and error(#kind, "msg"))
constructs a first-class Error value. Making
Error truthy prevents if result [ ... ] from
quietly misclassifying a failure as false/none
— you handle errors intentionally with:
expr otherwise fallback— catches any runtime error inexprand evaluatesfallback.val ?? fallback— coalescesnone/omtofallback.val?.field/xs?.[i]— safe navigation propagatingnone.attempt(expr)— evaluatesexprand returns its value ornoneon error.try(expr)— evaluatesexprand captures any raised/runtime failure as a first-classErrorvalue.try ... catch e ... finally ... end— structured handler block (catchesraise/throwand runtime errors;Defects likeAssertionErrorfromexpect/strictintentionally bypass ordinaryotherwise/attemptwhen invariant bugs must fail fast).
safe: (10 / 0) otherwise 0
maybe: attempt(10 / 0)
captured: try(10 / 0)
expect safe == 0 and maybe == none and error?(captured)
Why did
assert x == 42 tell me to use expect?
Because assert belongs to the Knowledge
Base, while expect checks program
expectations!
assert human("socrates")(andassert/axiom,assert/hypothesis, …) posits a logical fact into the Knowledge Base (Epistem).expect x == 42checks a boolean condition in tests and scripts:- Silent on pass by default
(
expect x == 42 [, "lazy failure note"]). expect/verbose x == 42printsPASSlines and a summary.expect/strict x == 42fails fast withAssertionErrorand a 2D column-aligned Power-Assert diagram showing every intermediate sub-expression!
- Silent on pass by default
(
x: 6 * 7
expect x == 42, "math still works"
7. Logic, Relations, Rules & the Knowledge Base
Why
didn't X = 10 create a Prolog logic variable at top
level?
In Prolog, every capitalized name is an unbound unification
variable everywhere. Because Axioma unites general-purpose programming,
TitleCase types/Concepts (Person, Integer),
and relational logic in one file, capitalized
identifiers (X, Who, Ancestor)
act as logic variables only inside relation
declarations, logical rules, and relational queries
({ X | X <- mortal(X) }). In ordinary
imperative/functional code, X = 10 is just an ordinary
variable binding!
How is Axioma's logic programming different from Prolog and Datalog?
Axioma gives you three explicit relational regimes instead of forcing one compromise:
- Default
relation(Epistemic KB engine): Deterministic, set-based deduction with 6-tier epistemic grounding (axiom > postulate > theorem > conjecture > hypothesis > datum), Belnap B4 paraconsistent truth, strict (whenever/<=/==>) + defeasible (typically/normally/<~~/~~>) rules,whyprovenance trees, andforget_cascadebelief revision. Clause order never causes infinite depth-first loops! relation/datalog: Enforces safe, range-restricted, stratified finite-domain Datalog rules with bottom-up fixpoint guarantees. A semiring segment weighs the answers:[logic/datalog/minplus | (X, Y) <- path(X, Y)]gives each answer its cheapest derivation overassert/weight:costs,maxtimes,maxmin,count, andwhygive the best single-path probability, bottleneck, derivation count, and minimal witness sets, and[logic/datalog/prob | …]runs exact possible-world Weighted Model Counting over thosewhywitnesses so shared-ancestor DAGs never double-count.relation/prolog: Opts into classic top-down ordered backtracking, unification,once, finite failure, and cut (!/prune) when translating or writing classic Prolog algorithms.
relation parent(p, c)
relation ancestor(p, c)
assert/axiom parent("ada", "byron")
assert/axiom parent("byron", "lovelace")
ancestor(X, Y) whenever parent(X, Y)
ancestor(X, Z) whenever parent(X, Y) and ancestor(Y, Z)
expect { D | D <- ancestor("ada", D) } == {"byron", "lovelace"}
What happens when contradictory facts enter the Knowledge Base — why doesn't everything explode?
In classical binary logic, a single contradiction (P ∧ ¬P) triggers the Principle of Explosion (ex falso quodlibet), proving every arbitrary statement true — fatal for real-world knowledge graphs, intelligence analysis, or multi-source agents.
Axioma supports Belnap's four-valued bilattice
(B4) alongside Kleene K3, Łukasiewicz
L3, Gödel G3, and classical
Boolean:
⊤ᵇ— supported true only⊥ᵇ— supported false only?ᵇ— neither (information gap / unknown)⊤⊥ᵇ— both true and false (localized conflict / glut — does not infect unrelated queries!)
Meanwhile, defeasible rules
(typically flies(X) whenever bird(X)) yield
conjecture-grade conclusions that step aside cleanly when
stricter evidence or cancel overrides them, without
corrupting axioms or theorems:
expect (⊤ᵇ and ?ᵇ) == ?ᵇ
expect (⊤ᵇ and ⊤⊥ᵇ) == ⊤⊥ᵇ
expect (⊥ᵇ and ⊤⊥ᵇ) == ⊥ᵇ
How
does neuro-symbolic programming work in Axioma — and why can't an LLM
claim axiom or theorem directly?
Axioma enforces a strict epistemic boundary: "neural proposes; symbolic checks, grounds, optimizes, and explains."
- Typed neural proposals & embeddings stay tentative
(
@hypothesis):ai.infer(prompt, TargetType [, opts])validates LLM JSON againstTargetTypeviachecked(...)and caps.groundingat"hypothesis"(or"datum"); requesting"axiom"or"theorem"faults immediately. Likewise,ai.soft_match(supporting offline hashed 3-grams, deterministic vectorcassettes, and live dense providers) caps non-identical cosine matches at"hypothesis". - Symbolic solvers earn
"theorem"& exact gradients:[logic/datalog/prob | …]and[logic/wmc | …]compute exactRationalpossible-world probabilities via Shannon-BDD Weighted Model Counting;grad,wmc_prob, andsemantic_lossbackpropagate exact gradients through logical lineages; andai.cegis_infer/[solver/cegis | …]uses Z3 counterexamples to repair neural@hypothesisformulas until universally verified across allInt/Realinputs (grounding: "theorem"):
type Alert = { supplier :: String, days :: Integer }
c: ai.cassette({"Fab 12 outage": "{\"supplier\": \"TSMC\", \"days\": 14}"})
proposal: ai.infer("Fab 12 outage", Alert, {cassette: c})
expect proposal.value.supplier == "TSMC" and proposal.grounding == "hypothesis" and proposal.valid
expect try(ai.infer("Fab 12 outage", Alert, {cassette: c, grounding: "theorem"})) is Error
prob_res: [logic/wmc | 1/2 :: halt("TSMC"); 4/5 :: uses("NVDA", "TSMC"); hit(X) <== uses(X, F) and halt(F); ? hit("NVDA")]
expect prob_res.result == 2/5 and prob_res.grounding == "theorem"
Can I pause a production system and continue with the same pending work?
Yes. A session keeps facts, logical justifications and refraction
between calls. rules.session() defaults to
rules.session(matcher="incremental"). Axioma uses the Rete
algorithm to retain partial matches and update affected joins as facts
change. Use rules.session(matcher="recompute") to match the
rules afresh at each matching boundary. Use s.step() to
fire one rule or s.run(limit=10) to bound the next group.
At a completed firing boundary, s.checkpoint(path) records
its current agenda. rules.restore(path) requires the same
rule-file contents and resumes that agenda. External actions that ran
after the last saved checkpoint can execute again after a crash.
s: rules.session()
h: s.insert([ada waits])
updated: s.modify(h, [ada ready])
expect/strict updated.id == h.id
expect/strict updated.revision == h.revision + 1
Why
didn't my asserted facts persist the next time I ran
axioma?
By default, axioma starts with no persistent
database attached (--no-kb) in ~0.04s so scripts,
tests, and CLI pipelines are fast, deterministic, and side-effect
free.
- Pass
--kb(uses~/.axiomakb/axiomakb.db, interoperable withAxiomaCascadeandAxiomaAgent) or--kb-path ./my.dbto persist facts across runs. - Use
transaction [ ... ]in memory or persistent KB sessions to commit atomically or roll back automatically if an error occurs inside the block.
8. Execution Modes, VM, Static Checking & Interop
What
is --vm and what is the "§911" rule? Why did
--vm refuse a program that runs normally?
Axioma has two execution engines:
- The tree-walking evaluator
(
axioma file.ax) — the normative reference runtime supporting 100% of the language (including open-world Concepts, KB rules, FFI, and solver blocks). - The bytecode compiler & VM
(
axioma --vm file.ax) — an optimizing engine governed by invariant §911:
§911:
--vmmust either produce byte-identical results to the reference evaluator, or refuse cleanly at compile/run time — it may never exit 0 with a silently different answer.
If your script uses a KB relation, runtime interface registration
(implement ... for), or another evaluator-only construct,
--vm refuses explicitly telling you why; run that script
without --vm.
How
does --typecheck work in a gradually typed language?
Annotations (x :: Integer,
func f(a :: String) :: Boolean, structural schemas, unions
A | B, intersections A & B) are
gradual:
- Unannotated code stays flexible; annotated boundaries enforce runtime contracts and unlock static checking.
axioma --typecheck file.axchecks type compatibility, arity, definite variable initialization, empty intersections, read-only collection views (Readonly Array of T), andif x is Tflow narrowing without executing the program.axioma --typecheck --run file.axruns the program only if static checking passes cleanly.
What runs in the browser Playground vs the native CLI?
- Browser Playground (
play.axiomalang.org, compiled to WebAssembly): Runs the full pure language client-side — exact numerics, sets, comprehensions, functions, ADTs, structs, regex, Concepts, Description Logic, multi-valued logics, and in-memory relations/rules. - Native CLI (
axioma): Adds persistent SQLite Knowledge Bases (--kb), filesystem/network I/O, inline SQL ([sql| ...]), Z3 SMT/SAT/ASP solver blocks ([smt| ...]), nativeimport python "..."andimport go "..."bridges, the LSP/DAP servers (axioma-lsp,axioma-dap), and the Model Context Protocol server (axioma --mcp).