Changeset View
Changeset View
Standalone View
Standalone View
swh/web/tests/resources/contents/code/extensions/lambda.sci
- This file was added.
// Author : Pierre Vuillemin (2017) | |||||
// License : BSD | |||||
function lambda(funStr) | |||||
// Mimics anonymous functions in Scilab. | |||||
// | |||||
// Syntax | |||||
// lambda('fun_name(var1,...,vari) = expr') | |||||
// | |||||
// Parameters | |||||
// fun_name : name of the function | |||||
// vari : arguments of the anonymous function | |||||
// expr : the actual function | |||||
// | |||||
// Description | |||||
// This routine enables to mimic anonymous functions in Scilab. These | |||||
// functions behave as handle functions in Matlab. More specifically, the | |||||
// data are instanciated when the function is created, not when it is | |||||
// called (as in Python). | |||||
// The main difference with 'deff' lies in the fact that an anonymous | |||||
// function can store data (see the example). | |||||
// | |||||
// Example | |||||
// a = 10; | |||||
// lambda('f(x)=a*x'); | |||||
// f(2) // returns 20 | |||||
// a = 20; | |||||
// f(2) // still returns 20 | |||||
// clear a | |||||
// f(2) // still returns 20, the initial value of 'a' is stored in f | |||||
// Separating the several parts | |||||
ieq = strindex(funStr,'=') | |||||
ini = list(part(funStr,1:ieq-1), part(funStr,ieq+1:$)) | |||||
out = tokens(ini(1), ['(',')']) | |||||
funName = out(1) | |||||
args = stripblanks(strsplit(out(2),'/,/')) | |||||
funContent = ini(2) | |||||
// Tokenizer | |||||
delimiters = ['*','+','-','/','^','(',')',',','&','|'] | |||||
TOKENS = tokens(funContent,delimiters) | |||||
varNames = list() | |||||
for t = TOKENS' | |||||
t = stripblanks(t) | |||||
if ~isempty(t) | |||||
if ~isnum(t(1)) | |||||
if and(t ~= args) | |||||
varNames($+1) = t | |||||
end | |||||
end | |||||
end | |||||
end | |||||
// | |||||
data = list() | |||||
for v = varNames | |||||
execstr('varValue = ' + v) | |||||
data($+1) = varValue//list(v, varValue) | |||||
newVarName = 'data('+string(length(data))+')' | |||||
funContent = strsubst(funContent,v, newVarName) | |||||
end | |||||
// output function | |||||
head = 'out = #innerFun('+strcat(args,',')+',data)' | |||||
deff(head,"out = "+ funContent) | |||||
lambdaFun = mlist(['sopiLambda','call','initFun','data'],#innerFun,funStr,data) | |||||
execstr(funName + '=resume(lambdaFun)') | |||||
endfunction |