What’s the point of using the set! assignment operator in scheme? Why not just rebind a variable to a new value using define?
> (define x 100) > (define (value-of-x) x) ;; value-of-x closes over 'x' > x 100 > (value-of-x) 100 > (set! x (+ x 1)) > x 101 > (value-of-x) 101 > (define x (+ x 1)) > x 102 > (value-of-x) 102 >
Though both
defineandset!will redefine a value when in the same scope, they do two different things when the scope is different. Here’s an example:As you can see, when we create a new lexical scope (such as when we
definea function), any names defined within that scope mask the names that appear in the enclosing scope. This means that when wedefinedxto4infoo, we really created a new value forxthat shadowed the old value. Inbar, sincefoodoes not exist in that scope,set!looks to the enclosing scope to find, and change, the value ofx.Also, as other people have said, you’re only supposed to
definea name once in a scope. Some implementations will let you get away with multipledefines, and some won’t. Also, you’re only supposed to useset!on a variable that’s already beendefined. Again, how strictly this rule is enforced depends on the implementation.