by ogogmad · 2y ago · 0 comments
I've looked it up and Common Lisp doesn't seem to provide such an option. Seems like an odd restriction. Oh, and the difference between LET, LET* and LETREC is another weird break from convention.
the exception is basic, where you could defint i or dim x(128) at any point, but it would be an understatement to say that basic's conventions were not widely emulated by other languages
I'm not sure what you mean about the difference between LET and LET* (the latter simply lets subsequent variable declarations refer to previously declared variables in the same block), and LETREC is not a builtin part of Common Lisp.
If you want to carefully delimit scope, doesn't Common Lisp (and other Lisps) provide PROGN? Seems like a less complicated approach.
> I'm not sure what you mean about the difference between LET and LET* (the latter simply lets subsequent variable declarations refer to previously declared variables in the same block
Why does LET even exist as an alternative to LET*? Why does Lisp even bother making this distinction?
Common Lisp requires one to clearly define the scope. PROGN does not create a scope.
> Why does LET even exist as an alternative to LET*? Why does Lisp even bother making this distinction?
Because there is a scope difference.
One can always do
(let (a b c)
(setf a 10)
...
(setf b 20)
...
(setf c (+ a b)
...)
Think of (let* ((a 10) (b 20) (c (+ a b)))
...)
as a short form for ((lambda (a b)
((lambda (c)
...)
(+ a b)))
10 20)Even Scheme gives this distinction an odd prominence that's not found outside the Lisp family. It seems reasonable that when I write code, I shouldn't have to stop and worry about which of the gazillion different LET forms is appropriate, especially in a high-level language which is supposed to help me write code (or read code) without worrying about irrelevant details like that.
Putting something like VAR everywhere now causes issues because it's not a form that returns a value. Also, there's no place to hang declare forms on it. And if it's executed conditionally, what does that mean? The var is declared on one branch but not the other?
https://www.nongnu.org/txr/txr-manpage.html#S-F2CAF1CB
For instance
(flow 1
(+ 2)
(let x) ;; x is 3 now
(+ 3)
(let y) ;; y is 6
(+ 4) ;; pipeline value is 10 now
(+ x y)) ;; 19 returned: (+ 3 6 10)
There is a (let (var1 init1) (var2 init2) ...) syntax supported also. Both these variants act as pass-through pipe elements: they bind variables that are in scope of the rest of the pipe.However, if you use the normal (let ((var init) ...) ...) syntax, then that is not special any more; it is just the regular let being threaded, like any other operator. It does not bind variables visible to the rest of the pipe.
Outside of this, there are only let and let* which resemble the Common Lisp ones.
Note that this construct makes sense even in pure code; it was not introduced for the sake of inserting side effects between variable definitions, but for capturing the output at specific points of the pipe, binding it to a name.
> And if it's executed conditionally, what does that mean? The var is declared on one branch but not the other?
Here is some C code:
if (cond()) {
preamble();
int a = 5;
do_stuff(a);
} else {
do_stuff(6);
}
And some Scheme code: (if (cond)
(begin
(preamble)
(define a 5)
(do-stuff a))
(do-stuff 6))
So why can't Common Lisp have the equivalent? (if (cond)
(progn
(preamble)
(var a 5)
(do-stuff a))
(do-stuff 6))
Instead, CL forces you to do this: (if (cond)
(progn
(preamble)
(let ((a 5))
(do-stuff a)))
(do-stuff 6))
Do you see the problem? Common Lisp wants you to declare every set of intermediate variables in a nested scope, leading to super-deep nesting unless you start breaking you function into small pieces for no reason (which then hurts readability).This is why languages die, when the old guard refuses to see that there are better ways of doing things than what they are used to.
> top level lexical scope
What does this mean? Every single other language lets you write:
var x = y;
Why is Lisp seemingly the only (imperative) language that doesn't?ANSI C89 requires that variable declarations only occur at the beginning of the scope.
That was long before C99; the project started around the middle 1980s, I think.
CLISP might benefit from being updated to C99, with all the files renamed to .c, and varbrace eliminated, but I don't think anyone's gotten around to it.
(let (foo bar baz)
(setf foo 2)
(other-code)
(setf bar (expt foo 2))
(more-code)
(setf baz 5))if you read documents from that era, the code that they write is wildly alien, because present day programming wasn't invented yet. things that you take for granted just didn't exist. common lisp and to a lesser extent scheme carry all that baggage for backwards compatibility.
so when lisp came out, it didn't have LET, and LET didn't appear until mid 70s. and it was added as a convenience macro for ((lambda (VAR1 VAR2 ...) ...) FORM1 FORM2 ...), which is how people did dynamic binding (also called lambda-binding) for a decade prior. evolution of lisp claims that LET came from lisp machine lisp, but people were independently inventing it all over the place, as a custom macro. depending on how your lambdas were evaluated or how your LET macro was written, you're not just assigning VARs simultaneously, you might not even have a guarantee of the order of evaluation of FORMs. but it got its job done, which is according to revised scheme manual "allowing the forms for the quantities to appear textually adjacent to their corresponding variables". this was a novel convenience at some point!
LET* was invented after LET as a convenience for LET, because sequential binding was even more convenient than binding in general. it would've made sense to then make LET* the "default" of some sort, but the subtle distinction stuck for reasons of legacy code, writing conventions, acquired preferences, and then it got crystalized and preserved for posterity in the common lisp standard.
However, a let based on lambda would have parallel binding. The evaluation of the forms would mainly come from the argument evaluation order of the lambda, where the macro would have to go out of its way to screw it up.
It's worth noting that Common Lisp has optional parameters. These use sequential binding like let*. So we could translate
(let* ((a (a)) (b (b))) c)
into (funcall (lambda (&optional (a (a)) (b (b)))))
The lambda is called with no arguments, so that the defaulting takes place, and that has all the semantics we need. (We could also similarly exploit &aux).The fact that CL's optional parameters use sequential binding kind of shows that it's the preferred mode.
The reason that the fixed parameters of lambda have parallel binding is that the values don't come from the lambda form itself, but from the arguments, which are already evaluated. So there is no way for a parameter value to be calculated from another parameter value. They come into existence at the same time.
Not so with optionals; they have default expressions, and those can refer to the prior variables.
Thus let came from lambda, and was understood in terms of fixed, required parameters. Required parameters come into the scope simultaneously, and so let variables came into scope simultaneously.
Other Algol-like languages including Algol itself also separate declarations and statements: Pascal, Modula, Ada, ...
In C90, you can have variables anywhere, but they must be wrapped in a compound statement. This has a number of advantages:
1. You can repeat variables:
{
int yes = 1;
setsockopt(fd, SOL_SOCKET, SO_WHATEVER, &yes);
}
{
int yes = 1;
setsockopt(fd, SOL_SOCKET, SO_OTHER, &yes);
}
2. You can move code around more easily, and move these sub-blocks into their own functions more easily, since they follow "declaration close to use".3. You control the end of the scope of the variables, not only the beginning. You know that after each of the above two closing braces, the yes variable is no longer in scope. (If there is a yes variable in scope, it must be coming from a parent scope; it is not "leaking" sideways.)
4. If you write a goto which goes around these encapsulated scopes, that goto does not jump into a region where the variable is uninitialized. Compare:
void fn()
{
goto end;
{
int x = 42;
}
end: ;
// x is not in scope here, OK
}
void fn()
{
goto end;
int x = 42;
end: ;
// x is in scope here, but not initialized!
}
For these reasons, I avoid mixing declarations and statements in C programming; the separation is a very good idea. It's enforced in Ada, where it is rationalized with safety arguments. Mixing declarations and statements encourages bugs. It lets you hack dubious solutions into the program without having to think about how its structure could be improved to do it cleanly.In Common Lisp and similar dialects, you can mix imperative code with variable definitions by using progn.
(let ((x (get-x-object)
(y (progn (perform-side-effect)
(get-y-object)))
(z (get-z-object)))
...)
On a small number of occasions, I've done the above in C, using the comma operator, to avoid mixed declarations and statements: int x = get_x();
int y = (perform_side_effect(), get_y());
It's a little dirty but not as dirty as mixed declarations and statements.Also note that there is no need for mixed declarations and statements, if your code is functional! In any of your code that emphasizes functional programming, you should not run into a need for this, because the entire purpose of the feature is to be able to stick a side effect between variable definitions, which has to be sequenced there.
The Scheme language has the feature of defining variables anywhere. You can use the define form in any scope, like inside a function:
(define (fun arg)
(define x 0)
(define y 1)
...)
How this works is that Scheme implementations perform a code walk which transforms these defines into nested let forms. Each sequential body of expressions has to be scanned for the presence of define and treated this way.It's pretty ugly; you end up with what looks like a self-contained form (define x 0) that is frobbing the surrounding lexical scope, such that another form not enclosed in it depends on its definition of x.
In Common Lisp and related dialects, anything that starts with "(def" is understood to be for top-level definitions only, which work by performing a run-time side effect when they are evaluated. (And so their effect is visible to later forms not due to lexical scope but due to the chronological order of execution.)
There is a strong metaprogramming advantage in having rigid variable binding forms like let. Because let has all the variables in one place, it is easy to interpret and compile. This is one of the things that helps a Lisp-in-Lisp metacircular evaluator be very short. If you have variables defined anywhere, it means that every form that contains statement-like forms must be scanned for those definitions. They are not in a fixed place in the AST: (let vars form ...). That is one big reason why if you implement Scheme's define, you want that to be expanded early, so that everything downstream just sees nice nested lets.
That's true when you write a goto that goes around scopes, and doesn't jump into them. However, you can still jump into the middle of an inner scope, where sometimes a variable might be uninitialized.
void c89_fn(int arg) {
if (arg > 0)
goto after;
{
int x = 42; /* or "int x; x = 42;" */
after:
/* x is in scope, but x could be uninitialized */
printf("%d\n", x);
}
}
For this particular example, GCC and Clang inline the definition of x as 42 unconditionally with any amount of optimizations on, but with -O0, both generate code that reads from a sometimes-uninitialized stack address. There's probably a more practical example that one could find.Also, my original example is invalid C++, as is yours.
C++ does not allow goto to skip variable initializations.
In C++, if you want to goto past some variable declarations, you have to do the right thing and encapsulate them into a block.
GCC's diagnostics look like:
goto.cc: In function ‘void f()’:
goto.cc:7:1: error: jump to label ‘end’ [-fpermissive]
end:;
^~~
goto.cc:3:8: note: from here
goto end;
^~~
goto.cc:5:7: note: crosses initialization of ‘int x’
int x = 42;
^I see. I think I get what you're saying: if you only put variable declarations at the top of the scope, then if you only jump to labels at the same statement depth as the goto statement, you won't skip initialization or assignment of uninitialized variables. Whereas, if you mix declarations and statements, you might end up with uninitialized variables even when you only jump to labels at the same statement depth as the goto statement. Is that what you're saying, or did I grasp something orthogonal to your point?
> C++ does not allow goto to skip variable initializations.
I didn't know that until now. However, if you change the function so that x is assigned after being declared, it still compiles and produces the same result.
void c89_fn(int arg) {
if (arg > 0)
goto after;
{
int x;
x = 42;
after:
/* x is in scope, but x could be uninitialized */
printf("%d\n", x);
}
}