New language feature "arguments" introduced in Scilab 2024.0.0

Do you know the new language feature arguments introduced in Scilab 2024.0.0?

The aim is to simplify the writing of input arguments validation, standardize messages and add readability of code by avoid blocks of checkers like:

if type(a) <> 1 | size(a) <> [2 3] then error("...");end

and potential speedup for function with lot of checks.

This new block takes this generic form

image

and previous example can be replaced by:

function test(a)
    arguments
        a (2, 3) {mustBeA(a, "double")}
    end
endfunction

For each input parameter, Scilab will be check dimensions compatibility, conversion capability and each validator (all must be verified) and if the input parameter is missing it will assign to default value.

All input parameters must be defined in the arguments block. And no check is mandatory, so if you want to check nothing, just let a line with the variable name

function test(a)
    arguments
        a
    end

    //algorithm
endfunction

test(1);

Dimensions

Here are a examples of dimension validation:

function test(a, b)
    arguments
        a (2, 3)
        b (1, 3)
    end

    //algorithm
endfunction

test(rand(2, 3), rand(1, 3));   //works
test(rand(2, 3), rand(3, 1));   //works, b will be transpose to match expected dimensions
test(0, 1);                     //works, a and b will be expanded to match expected dimensions
test(rand(3, 3), rand(2, 2));   //fails
function test(a)
    arguments
        //waits a 2 or 4 columns matrix
        a (:, [2 4])
    end

    //algorithm
endfunction

test(rand(1024, 2)); //works
test(rand(256, 3)); //fails
test(rand(512, 4)); //works

Conversions

Argument checking also manages automatic type conversion as follows:

function test(a)
    arguments
        a double
    end

    disp(type(a))
    //algorithm
endfunction

test(1);         // a is a double
test(uint8(42)); // a will be converted to a double

Validators

And here is how to force type checking:

function test(a)
    arguments
        a {mustBeA(a, "double")}
    end

    //algorithm
endfunction

test(1);         // works
test(uint8(42)); // fails

See the list of all validators

Default Value

If you want to set a default value for input argument, just use the following:

function test(a)
    arguments
        a = 12
    end

    //algorithm
endfunction

test(1);    // a == 1
test();     // a == 12

Since Scilab 2024.0.0, this new feature is already used in time module (see related merge request) and other modules will be updated in next versions…

As usual, don’t hesitate to share with us your use cases and issues.

1 Like