For example,
I want to check if an element is in a list. The algorithm is straightforward, let’s do it in C++
bool element_of( const std::vector<int>& lst, int elem ) {
for( int i( 0 ), ie = lst.size(); i < ie; ++i )
if( elem == lst[i] )
return true;
return false;
}
Since Scheme don’t let me use single if statement, I can’t do something similar to the C++ code above. Then I came up with a temporary variable, namely result. result will have initial value of #f, next I recursively call the function to check the next item in the list i.e. cdr lst … So my question is, does the variable which created with let restore its initial value each time it enters a new function call or its value stays the same until the last call?
On the other hand, using fold, my solution was,
(define (element-of x lst)
(fold (lambda (elem result)
(if (eq? elem x) (or result #t) result))
#f
lst))
Thanks,
Each
Letcall creates a new set of variables in the environment that the main body of theLetis being evaluted in. TheLetsyntax is a “syntactic sugar” for a lambda being evaluated with arguments passed to it that have been evaluted. For instanceis the same as writing
So you can see that in the
Letsyntax, the arguments are first evaluated, and then the body is evaluated, and the definitions ofaandbare utilized in the local environment scope. So if you recursively callLet, each time you enter the body of theLetcall, you are evaluating the body in a new environment (because the body is inside a newly defined lambda), and the definition of the arguments defined in the localLetscope will be different (they are actually new variables in a nested environment setup by the new lambda, not simply variables that have been mutated or “re-defined” like you would find in a C++ loop).Another way of saying this is that you’re variables will be like the local scope variables in a C++ recursive function … for each function’s stack-frame, the locally scoped variables will have their own definition, and their own memory location … they are not mutated variables like you might see in a loop that re-uses the same memory variables in the local scope.
Hope this helps,
Jason