Closures in Scilab

Scilab supports anonymous functions, which can form closures. Anonymous functions are useful when you want to define a function inline without having to name it.

function nextInt = intSeq()
    i = 0
    function n = anon()
        i = i + 1
        n = i
    endfunction
    nextInt = anon
endfunction

function main()
    // We call intSeq, assigning the result (a function)
    // to nextInt. This function value captures its
    // own i value, which will be updated each time
    // we call nextInt.
    nextInt = intSeq()

    // See the effect of the closure by calling nextInt
    // a few times.
    disp(nextInt())
    disp(nextInt())
    disp(nextInt())

    // To confirm that the state is unique to that
    // particular function, create and test a new one.
    newInts = intSeq()
    disp(newInts())
endfunction

main()

This code demonstrates the concept of closures in Scilab. Here’s how it works:

  1. We define a function intSeq() that returns another function. This inner function is defined anonymously within intSeq().

  2. The inner function closes over the variable i, forming a closure. Each time this inner function is called, it increments i and returns its value.

  3. In the main() function, we call intSeq() and assign its result (the inner function) to nextInt.

  4. We then call nextInt() multiple times, demonstrating that it maintains its own state of i across calls.

  5. To show that each closure has its own state, we create a new sequence newInts and call it once.

When you run this script, you should see output similar to:

1
2
3
1

This output demonstrates that nextInt() maintains its state across calls, incrementing from 1 to 3, while newInts() starts a new sequence at 1.

Note that Scilab’s syntax for closures and anonymous functions is different from some other languages, but the concept remains the same. The function within function structure allows us to create closures in Scilab.