Tuesday, March 29, 2011

Lexical Scoping, nice!

First, writing about recursiveness, there is nothing more recursive than * power (base, exp -1), so it goes and goes until it reaches 0 and multiplied by 1. Too bad for the speed disadvantage of calling functions over and over...

Now, what can I say about Lexical scoping, seems great but its a little crazy to grasp at once, so here is my try at that using the makeAddFunction example.

makeAddFunction is created with one argument amount, and inside is just a function add with another argument number.
add returns the value of numer+amount and then makeAddFunction returns the result of the add function.
Here comes the important bit, the creation of 2 variables that will act as variations of the makeAddFunction, so we have the addTwo and addFive variables, both take the type makeAddFunction, one with one it's argument as 2 and the other as 5 (hence their names), this arguments are the values of  amount.
At the end they call this variables, with show, each with an extra argument, that will be passed to the add function inside makeAddFunction.

So we get this :   "show (addtwo(1) + addFive(1))"

that at the end is
"show (makeAddFuntion(2) add(1) + makeAddFunction(5) add(1))"

and this would be how it works, the value of addTwo/Five goes to number, because the makeAddFunctions had their arguments already given, in amount, while the variables addTwo/Five where created.

This way the programmer doesn't need to say "hey by the way, this little number at the end of addTwo, is the variable number that is inside the function, ok Js? good..." having the ability of getting a variation of functionality with less lines of code.

next the ex...

No comments:

Post a Comment