Skip to content

Functions

In Seal, functions are first-class citizens. That means they are assignable to variables, can be passed to function calls as arguments just like any other values. There are some ways to define functions. We have already covered a few of them in previous sections. But in this section, we will dive into more details.

define is_odd(n)
    return n % 2 == 1

This code defines a local function called is_odd in current scope.

is_odd = define(n)
    return n % 2 == 1

Since functions are first-class citizens in Seal, you can create an anonymous function and assign that directly to a variable. For convention, the previous option is more recommended.

define optimized_is_odd(n) (n & 1) == 1

If closing parenthesis is not followed by newline right away and an expression comes, it is called lambda.

add = define(a, b) a + b

Again, first-class.

define $add(a, b) a + b
$add = define(a, b) a + b

define $add(a, b)
    return a + b

$add = define(a, b)
    return a + b

By putting $, you define that function as global.

define create_number_list(start, end)
    // end is exclusive
    if start == end
        return null

    i = start
    list = []
    if start < end
        while i < end do list->push(i++)
    else
        while i < end do list->push(i--)

    return list

define print_number_list(nums)
    if not nums // if nums is null
        print("(no numbers)")
    else
        print(nums)

nums = create_number_list(0, 10)
result = print_number_list(nums)

What do you think result will get printed as? Here is output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
null

"But print_number_list function doesn't return anything, why is that?" you might ask. Any function must return a value. It MUST. If a function doesn't encounter explicit return statement and reaches to the end, null is returned. That design choice is excellent for the Seal Runtime.

define some_func()
    return

define some_other_func()
    return null

print(some_func()) // null
print(some_other_func()) // null

They both will return null again. Empty return statements are just the same as returning null. However, you had best if you wrote return null statement explicitly if the function returns something. For the convention.

define do_this(x)
    /* some code */

    if not x
        return

    /* rest of it */

If it is a procedure (just executing, not supposed to use its return value), you can just type return to exit early. This is conventional.