Scilab Website | Contribute with GitLab | Mailing list archives | ATOMS toolboxes
Scilab Online Help
2025.0.0 - 日本語


Lambda functions

Scilab procedures and Scilab objects

Description

Lambdas or anonymous functions are a type of Scilab functions.

Lambda definition

Mainly used as "one liner" function to avoid to declare a function. Or when it is used once. Lambdas are the ability to catch variables states at declaration unlike classic functions. Lambdas can be assign to a variable at the same time of declaration, so they can be passed directly as function parameter.

  • Syntax:

    foo = #(x1, ...) -> (...)
  • Output parameters are implicit. So by default, you can only return a single parameter.

    ans will be used as return value.

    But in case several outputs are needed, varargout can be use like in classic functions

Calling function

  • Usually function calling syntax is [y1,...,yn]=foo(x1,...,xm). Shorter input or output argument list than definition ones may be used. In such cases, only the first variables from the left are used or set.

    The nargin and nargout variables can be used to obtain the actual number of input and output arguments.

    _ can be used to ignore output argument(s).

  • It is possible to define function with indeterminate number of input or output maximum number of arguments. This can be done using the varargin and varargout keywords. See the given links for details.

Miscellaneous

Lambdas are Scilab objects (with type numbers 13). And they can be manipulated (built, saved, loaded, passed as arguments,...) as other variable types.

Examples

//simple use
pyth = #(x, y) -> (sqrt(x ^ 2 + y ^ 2));

pyth(3, 4)
pyth(12, 16)

//catching of variable
y = 4;
pyth = #(x) -> (sqrt(x ^ 2 + y ^ 2));
clear y;

pyth(3)

//used as function parameter

t = 0:0.1:%pi;
y = ode(0, 0, t, #(t, y) -> (
    y ^ 2 - y * sin(t) + cos(t)
));

plot(t, y);

//lambda factory

function f=comp(threshold)
    f = #(x) -> (x < threshold);
end

//return a lambda configured by the input variable
comp_10 = comp(10);
[comp_10(3), comp_10(15), comp_10(22)]
comp_10([3 15 22])

//return another lambda configured by the input variable
comp_20 = comp(20);
[comp_20(3), comp_20(15), comp_20(22)]
comp_20([3 15 22])

See also

  • functions — Scilab プロシージャおよび Scilab オブジェクト
  • varargin — 入力引数リストの引数の数を可変にする
  • varargout — 出力変数リストの引数の数を可変にする
  • ans — 答え

History

バージョン記述
2025.0.0 lambda introduction.
Report an issue
<< hypermatrices types library >>

Copyright (c) 2022-2024 (Dassault Systèmes)
Copyright (c) 2017-2022 (ESI Group)
Copyright (c) 2011-2017 (Scilab Enterprises)
Copyright (c) 1989-2012 (INRIA)
Copyright (c) 1989-2007 (ENPC)
with contributors
Last updated:
Thu Oct 24 11:17:38 CEST 2024