Wednesday, 22 January 2020

Generate Functions with Different Constants in Python, JS

Source Code (Python):
#Any function
def f(X):
return X**2;

#Constants for generating functions
Ts = [1,2,3];

#Generate functions
Fs = [(lambda X,T=T: f(X)+T) for T in Ts];

#Call generated functions with default constants
print(Fs[0](3));
print(Fs[1](3));
print(Fs[2](3));

#Call generated functions with specific constants
print(Fs[0](3,1));
print(Fs[1](3,2));
print(Fs[2](3,3));
#EOF

Result:
10
11
12
10
11
12

Source Code (JavaScript, Node.js):
//Shortcuts
log = console.log;

//Any function
function f(X){
return X*X;
}

//Constants to generate functions
Ts = [1,2,3];
Fs = [];

//Function generator loop
for (I in Ts) { //Get index list
..T = Ts[I];
..F = (T => { //A function instance
....return function(X){
......return f(X)+T;
....}
..})(T);
..Fs.push(F);
}

//Test generated functions
log(Fs[0](3));
log(Fs[1](3));
log(Fs[2](3));
//EOF

Result:
The same

1 comment:

  1. Internet online marketing experts found in the blog, webmaster forums and online publications. com, where you can learn about the latest Google updates the new method can make money website. Leadgeneration

    ReplyDelete