LEP-005: Functions

Created:Friday, May 6, 2022
Author:David Delassus
Category:Language Design


This LEP specifies the syntax of functions and lambda expressions (or closures).


Functions are the core feature of any functional language, if not every programming language.


Function signature

A function must define the type of its arguments and its return value:

func foo(a: number, b: string) -> @ok | (@error, atom) {
  # ...

This indicates to which class the function belongs to:

foo is func[(number, string) -> @ok | (@error, atom)];

NB: The class func[arguments -> return] contains every function with the same signature.

Function body

The body of a function consists of a sequence of expressions. The value of the last expression is returned:

func double(a: number) -> number {
  a * 2;

Generic functions

A function can take type parameters, to reduce code duplication:

func swap<T, U>(a: T, b: U) -> (U, T) {
  (b, a);

Which can be called like this:

swap::<int, string>(42, "hello");

First class citizens

Every function can be assigned to variables and passed as arguments or returned:

module "example.funcs";

func make_adder(a: number) -> func[(number) -> number] {
  func(b: number) -> number {
    a + b;

func main() -> @ok {
  add_five := make_adder(5);
  assert add_five(1) = 6;

Type checking

When a function is called, Letlang will check at runtime the type of all supplied arguments. Before returning, Letlang will check at runtime the type of the return value.

NB: Type checking is always done at runtime. Compile-time type checking may also be implemented but it is not mandatory.

Early return

The only form of early return is done by throwing an exception[1].

Function color

Letlang functions have no color[2]. It is up to the caller to determine if the function should be synchronous or asynchronous.

Rejected Ideas

Return statement

The return statement as a form of early return will not be supported.

Opinion: Having a single point of return help reduce the cognitive load of the code.


1LEP-006: Side effects/lep/006/
2What color is your function?https://journal.stuffwithstuff.com/2015/02/01/what-color-is-your-function/