Skip to content

Functions

fn greet name
console.log[name]

Compiles to:

function greet(name) {
console.log(name);
}

The to form creates a one-liner function body. Named functions do not have implicit return — use to return for explicit return.

fn greet name to console.log[name]
function greet(name) { console.log(name); }
fn double x to return x mul 2
function double(x) { return x * 2; }

Simply omit the parameters:

fn say-hello
console.log[///Hello!///]
function say_hello() {
console.log("Hello!");
}

With expression body:

fn say-hello to console.log[///Hello!///]
function say_hello() { console.log("Hello!"); }

Use ; to separate parameters:

fn add a; b
return a add b
function add(a, b) {
return a + b;
}
const double be fn x to x mul 2
const double = (x) => x * 2;
const get-time be fn to Date.now[]
const get_time = () => Date.now();
const process be fn data
console.log[data]
return data
const process = (data) => {
console.log(data);
return data;
};
async fn fetch-data url
const res be await fetch[url]
return res
async function fetch_data(url) {
const res = await fetch(url);
return res;
}

Async anonymous functions work like regular anonymous functions with async prefix:

const handler be async fn event to await process[event]
const fetcher be async fn url
const res be await fetch[url]
return await res.json[]
const handler = async (event) => await process(event);
const fetcher = async (url) => {
const res = await fetch(url);
return await res.json();
};

With multi-line bracket support, anonymous functions can be passed as arguments in method chains:

promise.then[fn result to console.log[result]].catch[fn err to console.error[err]]

Multi-line form:

fetch[url].then[
fn response
return response.json[]
].then[
fn data
console.log[data]
].catch[
fn err
console.error[err]
]
fetch(url).then((response) => {
return response.json();
}).then((data) => {
console.log(data);
}).catch((err) => {
console.error(err);
});

Use [] instead of ():

greet[///world///]
add[1; 2]
console.log[///hello///]
greet("world");
add(1, 2);
console.log("hello");

In JavaScript, nested calls like a(b(c), d) use (). In Purus, since [] is used for both arrays and calls, use ; to separate arguments:

-- JS: a(b(c), d)
a[b[c]; d]
-- JS: a(b, c(d, e))
a[b; c[d; e]]
-- JS: console.log(Math.max(1, 2))
console.log[Math.max[1; 2]]
-- JS: fn(a(1, 2), b(3, 4), c)
fn[a[1; 2]; b[3; 4]; c]
-- JS: outer(inner1(x), inner2(y, z))
outer[inner1[x]; inner2[y; z]]
a(b(c), d);
a(b, c(d, e));
console.log(Math.max(1, 2));
fn(a(1, 2), b(3, 4), c);
outer(inner1(x), inner2(y, z));
fn add a of Number; b of Number gives Number to a add b

Type annotations with of and gives are erased in the JavaScript output.

fn get-value
return 42