Skip to content

Functions and closures ​

Functions ​

fn declares a function and names its parameters' types. The result type is inferred when you leave it out, except in a recursive function. So is the error type of a function that can fail: fn load(id: string): Todo may still fail, and its callers see how (Errors).

weft
fn pad(s: string, width: number = 2, fill: string = "0"): string {
  return s.padStart(width, fill)
}

export fn clock(h: number, m: number): string {
  return `${pad(h.toString())}:${pad(m.toString())}`
}

export fn sumAll(...xs: number[]): number {
  return xs.sum()
}

export fn fib(n: number): number {
  return if n < 2 { n } else { fib(n - 1) + fib(n - 2) }
}

Parameters can have defaults, be optional (note?: string is a string? that defaults to null), and the last one can collect the rest (...xs). Functions declared in a block can call each other in any order. There is no function keyword: writing it is an error that points to fn.

Destructured parameters ​

A parameter can be a pattern, with its type after it. Defaults inside the pattern fill the fields the type marks optional:

weft
import { hypot } from "std/math"

type CardProps = { title: string, compact?: boolean }

export fn card({ title, compact = false }: CardProps): string {
  return if compact { title } else { `## ${title}` }
}

export fn dist([x, y]: [number, number]): number {
  return hypot(x, y)
}

A destructured parameter is read-only, so a mut parameter can't be one.

Arrow functions ​

Arrows are expressions: (a, b) => a + b, or with a block body. Their parameter types come from where they are used, so xs.filter(t => t.done) needs no annotation. An arrow that returns a record wraps it in parentheses:

weft
type Todo = { id: number, title: string }

export fn titles(todos: Todo[]): { id: number, label: string }[] {
  return todos.map(t => ({ id: t.id, label: t.title.toUpperCase() }))
}

Arrows have no return type annotation. When the result needs one, write an fn.

Methods on your own types ​

x.f(args) calls the built-in method f of x's type if there is one. Otherwise it calls a function f in scope whose first parameter takes x. So functions over your types read like methods, with no classes:

weft
type Todo = { title: string, done: boolean }

fn isOpen(t: Todo): boolean {
  return !t.done
}

fn open(todos: Todo[]): Todo[] {
  return todos.filter(isOpen)
}

export fn openTitles(todos: Todo[]): string[] {
  return todos.open().map(t => t.title)
}

Closures that run now ​

A function passed to a parameter runs during the call by default, as the callbacks of filter, map and forEach do. Such a closure reads and writes the enclosing function's locals directly:

weft
export fn total(xs: number[]): number {
  let mut total = 0
  xs.forEach(x => {
    total += x
  })
  return total
}

Closures that run later ​

A closure escapes when it runs after the call that made it: a timer callback, an event handler, a closure stored in a record or returned. An escaping closure captures copies of the locals it reads, taken when it is created, and it can't write them:

rejected by the compiler (E3004)
weft
import { setTimeout } from "std/time"

export fn later(): number {
  let mut count = 0
  setTimeout(() => {
    count += 1
  }, 100)
  return count
}

Writing count there would change a copy nobody sees, so the compiler rejects it and says what to do: make count component state, or return the value. Component state is different: closures reach it by name, never by capture, so a handler can always write it (Components).

A function that keeps a callback for later marks the parameter escaping:

weft
import { setInterval } from "std/time"

export fn every(ms: number, f: escaping () => void): number {
  return setInterval(f, ms)
}

Without the mark, storing or scheduling f is an error, and the compiler suggests it. A closure that runs during the call may fail, and the call then fails with its error (try xs.map(s => try parseNumber(s))); one that runs later can't, since no caller is left to take the error (Errors).

Tagged strings ​

A name directly followed by a string is a tagged string: tag"text {x} more" calls tag(parts, x). parts.strings holds the literal pieces (one more than the values), and the values arrive as the remaining arguments, typed by the tag's parameters. Inside one, {{ and }} write braces.

weft
fn shout(parts: Parts, ...values: string[]): string {
  let mut out = parts.strings[0]
  for (v, i) of values { out += v.toUpperCase() + parts.strings[i + 1] }
  return out
}

export fn hello(name: string): string {
  return shout"hello, {name}! {{braces}}"
}

The standard library's tags can be checked when the program compiles: std/db's sql"select … where id = {id}" will check the query against the schema and type the rows it returns.

Query closures ​

lib/open.weft
weft
import { table, schema, primary, index, sqlite, public } from "std/db"

type Todo = { @primary id: string, title: string, @index done: boolean }
let todos = table<Todo, Todo>("todos", { read: public() })
let db = (try await sqlite(schema({ tables: { todos } }), ":memory:")).as(null)

export async fn open(q: string): Todo[] {
  return try await db.query.todos().filter(t => !t.done && t.title.startsWith(q))
}

A standard-library function can take a parameter typed Query<F>. Its argument must be an arrow written in place; the function gets it both as a function (q.call(…)) and as a typed expression tree (q.tree), which it can translate, as std/db turns filter(t => !t.done && t.title.startsWith(q)) into SQL. The arrow is checked as usual, and the declaration may limit what its body uses. Only the standard library declares Query parameters.

async and await ​

An async fn returns a Task. Its written result can be Task<R> or just R; both mean the same. await waits for a task. Task.all waits for several:

weft
import { sleep } from "std/time"

type User = { id: number, name: string }

async fn loadUser(id: number): User {
  await sleep(10)
  return User { id, name: `user ${id}` }
}

export async fn loadAll(ids: number[]): User[] {
  return await Task.all(ids.map(id => loadUser(id)))
}

await always suspends, even on a task that is already finished, and the code after it runs as a new turn. An async fn can't have mut parameters, because a borrow can't last across an await:

rejected by the compiler (E3006)
weft
import { sleep } from "std/time"

type Counter = { n: number }

export async fn bump(mut c: Counter) {
  await sleep(1)
  c.n += 1
}

A Task you create and then ignore is a warning: await it, store it or return it. A call written as a statement on its own is the exception: it starts the task and lets it run.

A task of a function that can fail is a Task<R ! E>. Calling the function doesn't fail; awaiting the task does, so the await takes the try: let user = try await loadUser(id) (Errors).

Weft is in development. The reference is the spec as it stands today.