views:

134

answers:

2

Hi!

Can you give me some examples of tasks unsuited for dynamically scoped lisps? I'm failing to see how the Lexical scope is so much better and not just a matter of changing the coding style, so I'd love to code something and see it with my own eyes.

Thanks!

+6  A: 
(define (add n) (lambda (m) (+ n m)))
(define add4 (add 4))
(map (add 7) (list 1 2 3))

But that's just one tiny random example. If you dig far enough, you'll find several tons of additional reasons. For a more thorough discussion, you should really go through some textbook. My recommendation for this would be PLAI.

Here's one more demonstration:

(define tax 0.17)
(define (add-tax amt) (+ amt (* amt tax)))

It looks like add-tax is a function that returns the given amount with the correct tax rate added -- but you can never rely on this being the case. For example, it could be called like this:

(let ((tax -0.17)) (add-tax 100))

and you'd get completely wrong answers. But things are even worse if your language is truly dynamically scoped: you cannot rely on any binding, including functions. Consider this:

(let ((+ -)) (add-tax 100))

And BTW Elisp and CL don't suffer from this problem so directly, using things like a double namespace, and rules about shadowing "built in" bindings.

Eli Barzilay
dynamically rebinding functions is mostly not done in CL, since CL by default uses lexical binding for functions too. Different than Elisp, which has no lexical binding at all.
Rainer Joswig
A: 

It's worth reading the Wikipedia article on scope.

Functionally, it only matters when you have variables that aren't bound in the current scope. So, if you don't have any free variables, it doesn't matter.

Eliz Barzilay's answer is a good example of a lambda with a function that has a symbol (n) that will have a different binding in dynamic/static scope.

From what I know, languages with lexical scoping can be compiled a little more, because at compile-time the compiler can determine all the variable references, as opposed to dynamic scope which must look up the variable reference at run-time.

Trey Jackson
The `lambda` expression that I wrote *doesn't* have any unbound identifiers -- *if* you have lexical scope. If you don't, then any identifier is either bound or not -- according to whatever way you got to call it.
Eli Barzilay
@EliBarzilay Correct, I'll clarify what I meant.
Trey Jackson