Functions

Rook — 1.0 specification

func add(a, b number) number {
    return a + b
}

func greet(name string) {          // without a result type it returns nothing
    console.log(`Hello, ${name}`)
}
function add(a, b) {
  return a + b
}

function greet(name) {
  console.log(`Hello, ${name}`)
}

Adjacent parameters of the same type can be grouped: a, b number is the same as a number, b number.

An object type is a result when the body follows it, func origin() { x, y number } { ... }; in parentheses, ({ x, y number }), it is one anywhere.

Default values and the rest of the arguments

func greet(name string = "you", times = 1) string {
    return name.repeat(times)
}

func log(level string, ...parts any[]) {
    console.log(level, ...parts)
}

greet()                    // "you"
log("info", "saved", 3)

Multiple results

func divmod(a, b number) (number, number) {
    return Math.floor(a / b), a % b
}

const q, r = divmod(17, 5)
const _, rest = divmod(17, 5)      // _ skips a value
function divmod(a, b) {
  return [Math.floor(a / b), a % b]
}

const [q, r] = divmod(17, 5)
const [, rest] = divmod(17, 5)

The rules are those of Go:

Anonymous functions

const square = func(x number) number { return x * x }
const sum = (a, b number) => a + b
const doubled = nums.map(x => x * 2)      // the type of x comes from the context

Arrow functions are as in JS, with Go-style types. If the type of a parameter cannot be inferred from the context, it must be written.

A func literal compiles to an arrow function too, so this inside it is the this of the surrounding method, not a new one as with function in JS.

defer

defer postpones a call until the function exits: on return, at the end of the body or on an exception.

func readConfig(path string) (string, error) {
    const fd = fs.openSync(path, "r")
    defer fs.closeSync(fd)

    const text = fs.readFileSync(fd, "utf8")
    if text == "" {
        return "", error("empty config")
    }
    return text, null
}
function readConfig(path) {
  const fd = fs.openSync(path, 'r')
  try {
    const text = fs.readFileSync(fd, 'utf8')
    if (text === '') {
      return ['', new Error('empty config')]
    }
    return [text, null]
  } finally {
    fs.closeSync(fd)
  }
}

The rules are those of Go:

func countdown() {
    for let i = 0; i < 3; i++ {
        defer console.log(i)
    }
}
// countdown() prints 2, 1, 0

For several actions there is a block form; its content runs as a whole on exit:

defer {
    conn.close()
    console.log("connection closed")
}

If all the defers are at the top level of the function's body, the compiler writes nested try/finally, as in the example above. If a defer is inside an if or a loop, the deferred calls are collected in a stack and run in finally.

Markdown source on GitHub