In Lisp (I am still learning Lisp with SBCL), local variables are declared with let, and the scope is only within that expression. Why is that? Unlike in other imperative languages like C/C++/Java..., where we can freely use local variables anywhere in its function scope.
Just another little insight into what let is. It is basically an application of an anonymous function "spelled backwards".
I will use JavaScript for the illustration because it is more C-like language and it illustrates the concept quite well.
(function(variableA, variableB){
console.log("variableA = " + variableA);
console.log("variableA * variableB = " + variableA * variableB);})(6, 7);
Now, let's name the parts: from function to ;} is the function definition. (definition)(arguments) is the application. Let expression does essentially the same thing, i.e. it invokes an anonymous function with arguments, which you use inside that function as variables. So, if you consider the previous example, rewriting it in let form would make something like:
(let(variableA = 6, variableB = 7){
console.log("variableA = " + variableA);
console.log("variableA * variableB = " + variableA * variableB);});
(JavaScript doens't support let, yet, so above isn't a working code example, but it should be an illustration)
You should also note that it is not exactly that simple. Because in more complex cases you may want to reference one of the arguments when constructing another - and then you would use (let* ...), or you would want to use functions as arguments of this expression, and then you would use (flet ...) or (labels ...). But the general idea is the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With