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
andnargout
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)
//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
History
バージョン | 記述 |
2025.0.0 | lambda introduction. |
Report an issue | ||
<< hypermatrices | types | library >> |