Core language showcase
Every snippet below was checked against the v3.1.36 lexer, parser and interpreter. The keyword set is exactly: let const print if else while for in function return true false null and or not break continue import assert parallel try catch finally throw export as async await match using.
Values, bindings and strings
let name = "PeaLang"
const release = 3.1
let flag = true
let missing = null
print "Hello {name} {release}"
print "literal braces: {{ok}}"
let is mutable and optional-typed; const requires an initializer. Numbers are integers or decimal floats; strings support the escapes \n \t \r \" \' \\.
Collections, comprehensions and destructuring
let xs = [1, 2, 3, 4]
let doubled = [x * 2 for x in xs if x > 1]
let pairs = [[1, 10], [2, 20]]
let values = [v for [k, v] in pairs]
let squares = {k: v * v for [k, v] in items({"a": 2, "b": 3})}
let [a, b] = [10, 20]
let {name, score} = {"name": "Ada", "score": 91}
print "{a}+{b}={a+b} {name}:{score}"
let it = iter([1, 2, 3])
print has_next(it)
print next(it)
Comprehensions and list/map patterns are real runtime features. Explicit iterators are a Preview surface labelled language.iterators: the low-level contract includes make_iterator, iterator_next(default=...), has_next, peek and close_iterator. There are no set or tuple literals: use lists and maps.
Functions, operators and null safety
let mapped = list(map(function(x) { return x * 10 }, [1, 2, 3]))
let evens = list(filter(function(x) { return x % 2 == 0 }, [1, 2, 3, 4]))
let city = user?.profile?.city ?? "unknown"
let ok = handler?.()
print 2 ** 10
print "ell" in "hello"
print get({"a": 1}, "missing", 0)
print safe(function() { return risky() }, "fallback")
Supported operators include + - * / % == != < > <= >= and or not in, compound assignment += -= *= /=, null coalescing ??, exponentiation **, optional chaining ?. and optional calls ?().
Control flow and pattern matching
let status = 404
let label = match status {
200, 201 => "ok"
404 => "not found"
_ => "error"
}
match {"name": "Ada"} {
{name} => print name
_ => print "unknown"
}
for x in [1, 2, 3] { print x }
while false { print "never" }
match supports comma-separated or-patterns, optional if guards, wildcard _, list and map patterns, and either an expression or a block body. There is no case keyword and no | separator.
Structured errors
function risk(score, limit) {
if score == null {
return error("ValueError", "missing score", "E_SCORE")
}
if score > limit {
return error("ValueError", "limit breach", "E_LIMIT", null,
{"score": score, "limit": limit})
}
return {"ok": true, "score": score}
}
let result = risk(95, 80)
print result["kind"]
print result["code"]
let ctx = result["context"]
print ctx["score"]
error(kind, message, code, cause, context) accepts a known kind (TypeError, ValueError, KeyError, and so on). try/catch/finally supports typed catches such as catch TypeError e. Error values carry schema, kind, message, code, cause, context and source spans. The stable value schema is pealang-error-v1 (ERROR_VALUE_SCHEMA); the Python-level contract is ErrorValue; hosts raise PeaError(message, span=None, source_name="<input>", frames=None, *, code="", cause=None, context=None) and materialise structured values with build_error(kind, message="", code="", cause=None, context=None).
Optional types, generics and protocols
protocol Printable { function to_string() -> String }
function show<T: Printable>(value: T) -> String {
return "printable"
}
function first<T>(items: List<T>) -> T? {
return null
}
trait Serializable
let x: Int = 5
print show(x)
Type annotations, generics, protocols and traits are static-analysis contracts. erase_types() strips them before runtime parsing, so they provide diagnostics and documentation value without runtime objects. The Python-level surface is TypeChecker, GenericFunctionContract and ProtocolContract; typecheck-project also checks the project module graph and reports cycles.
Modules and resources
import "api.client" as client
print client.value
using conn = open_connection() {
print conn.query("select 1")
}
open_connection here is a host-provided binding; the using statement is real syntax in v3.1.36. Resource scopes are bounded through the scopes.current/snapshot/dispose namespace.
Standard library surface
Twenty-nine permissioned modules live under std.*: collections, string, math, datetime, json, csv, regex, file, path, http, crypto, logging, testing, concurrent, web, analysis, interop, ux, stats, sql, cache, uuid, cli, config, template, serialize, graph, queue, env. The 196 global names include group_by, sort_by, deep_merge, sha256, url_encode, median, clamp, chunk, pluck, zip_object, format_number and many more.
print std.collections.chunk([1,2,3,4,5], 2)
print std.string.slugify("Hello PeaLang World")
print std.math.clamp(12, 0, 10)
print std.json.stringify({"ok": true})
print sha256("pea")
class or decorator syntax in .pea source, switch, raise, elif, set/tuple literals and source-to-source transpilation. Do not port idioms that depend on them.See the code library for these constructs in full industry examples.