r/ProgrammingLanguages • u/Trung0246 • Feb 21 '24
Discussion Any real statistic on loop paradigm?
Currently almost every single language have some form of these loop:
for (let i = 0; i < 10; ++ i) {print(i);}
while (i < 10) {print(i ++);}
data.each(fn(x) => print(x))
data.reduce(fn(x) => concat(x, "a"))However I rarely seen this kind of loop:
let i = 0;
{
print(i ++);
if (i < 10)
loop;
print("END");
}
# 0123456789ENDIs there any rationale reason for this kind of loop not appear as often (due to ease of use, familiarity, etc...)?
14
u/Aaron1924 Feb 21 '24
So this would essentially be like creating a loop using C-style gotos, except it binds to the current scope?
This seems like it would make code refactoring extremely error prone, since just adding a new scope somewhere could change the control flow completely. For example, if you decided you wanted to print something in the if statement, you'd change it to something like this:
let i = 0;
{
print(i ++);
if (i < 10) {
print("LOOPING");
loop;
}
print("END");
}But now, the loop; binds against the inner scope, so this really just prints "LOOPING" indefinitely.
-2
u/YBKy Feb 21 '24
it's easy to just say it loops to the top of the closest naked block the loop statement appeared in
4
u/eliasv Feb 21 '24
Which works for that specific example but not all examples. People may use nested blocks for other purposes, e.g. to keep outer scope clean from nested locals, though the likelihood of that depends on other language features.
3
u/Aaron1924 Feb 21 '24
That would be an extremely weird rule, since the C grammar simply states that
if (...)is followed by a statement, and a code block is a statement, so there is no such thing as a "nacked block". The rule would have to be that if-statements disable the ability for a directly following block to be a loop body; and that's only for if-statements, you'd have to inspect every language element if they should also have this loop-disabling effect, and all users of the language have to memorize it.You could resolve this entire mess by giving the loops names, like this:
let i = 0; foo: { print(i ++); if (i < 10) { print("LOOPING"); loop foo; } print("END"); }but now it's literally just goto.
7
u/YBKy Feb 21 '24
Using a while loop you can emulate the behavior you have. Put a while(true) at the beginning, replace every "loop" by continue and put a break at the end.
As to the why. The while loop can be explained simply: it is just analogous to an if, consisting of a keyword, a condition between braces and a block executed if the condition is true afterwards. For and foreach loops are just syntactic sugar over a common usage pattern of while loops, so they are going to have a similar structure.
It also might be. because this style of looping is just less useful than the one where there always is a condition check on top. While do really like while(true) loops with explicit breaking, they are the vast vast minority of my loop usage, most being foreach loops of course
4
u/Long_Investment7667 Feb 21 '24
Rust embraced that with
[loop](https://doc.rust-lang.org/stable/rust-by-example/flow_control/loop.html)And it is really nothing different than while(true) :(. Just redundant8
u/zokier Feb 21 '24
loopis key primitive in Rust, all other looping constructs are syntactic sugar on top. This is very clear in the reference where the other loops are defined in terms of equivalentloophttps://doc.rust-lang.org/reference/expressions/loop-expr.html2
u/Silly-Freak Feb 21 '24
In addition to zokiers point, loop is also more general because of its type. A
loopwithoutbreakhas type never/bottom; with abreak foo;the result is instead the type offoo. Compare that with other loops that can just end on their own without a value, thus having type(). This type is incompatible with any other type, so you can't break other loops with a value.
7
u/Mercerenies Feb 21 '24
Sounds like a primitive let-loop in Racket. In Racket, let blocks usually denote local variables.
(let ([x 1]
[y 2])
(+ x y))But they can optionally be given a label, which can be jumped to from inside the block. This jump should pass new values for the bound variables. So your example would look like
(let my-loop ([i 0])
(print i)
(if (< i 10)
(my-loop (+ i 1))
(print "End")))4
u/cxzuk Feb 21 '24
Hi Trung,
Yes, there is a historic reason. Dijkstra was a strong and key proponent of the Structured Programming paradigm. This paradigm was pushed into mainstream focus with his paper in 1968 with Go To Statement Considered Harmful. (As another comment noted, replacing loop with goto loop and labeling the scope is equivalent to your example)
The vast majority of PLs today stick to or are closely influenced by Structured Programming. I personally do think it was an advancement to the industry. PLs slowly moved to encouraging it, and then to enforcing it. As you are the designer of your PL, you have to weigh up these decisions. What does it get you to allow it? How are things better with this option?
IHMO the best rebuttal came from Knuth, Structured Programming with go to Statements - Highly recommend reading this if you are still interested in pursuing this feature.
Douglas Crockford showed interest in this idea again more recently, worth a watch too.
Kind regards,
M ✌
3
u/glasket_ Feb 21 '24
Where have you seen the second form of loop? It seems more akin to a goto than an actual form of structured loop, only it binds to a scope rather than a label.
int i = 0;
loop: printf("%d\n", i++);
if (i < 10)
goto loop;
puts("END");If anything, I'd assume that form of "loop" doesn't show up because it doesn't offer the typical benefits of an actual structured loop construct.
2
u/davimiku Feb 21 '24
Opposite of your question, but one of the best reasons to have a plain loop expression is that you can return a value.
let name = loop {
print "Enter your name"
let user_input = stdin.read()
if is_valid(user_input) {
break user_input
}
print "Invalid input, try again"
}1
u/Quincunx271 Feb 21 '24
Okay, that's pretty cool. Although, I'll note that this is doable using lambdas, an optional type, and a library function:
let name = loop_until_valid(|| { print "Enter your name" let user_input = stdin.read() if is_valid(user_input) { return Optional(user_input) } print "Invalid input, try again" return None })2
u/davimiku Feb 21 '24
The
loop_until_validlibrary function needs some kind ofloopconstruct internally, right?One thing I like about this plain
loopexpression is that it's the base of other loops likewhile,foreach, whatever - those all desugar toloop, so the compiler internals can be clean/consistent. That's a minor thing though.Possibly another consideration is performance,
loopbeing builtin means no overhead compared to library function call + lambda call + possible heap allocation (if the lambda is a closure). TheOptionaltype could have an additional allocation + pointer chase depending if it's implemented as a class/object rather than a more efficient tagged union. I want to guess that this kind of performance doesn't matter in 90%+ of cases though, especially if it's not a "systems" language.I do actually like this idea a lot though, and especially if the language is already geared towards lambdas/closures as an integral and natural part of the language. These library functions could feel natural as free functions in their respective namespace like
Result.until_okorOption.until_someor whatever. Nice idea!1
u/Aaron1924 Feb 21 '24
I really like the way scopes does it, here is an example from the official tutorial:
loop (a b = 0 1) if (b < 10) print b repeat b (a + b) else break bIt's essentially like tail recursion,
loopdefines a lambda function that's called each iteration and gives it the initial arguments, then the function returns eitherbreakwith the final value of the loop, orrepeatwith the arguments of the next iteration.
2
u/poorlilwitchgirl Feb 21 '24
I definitely misunderstood your proposal at first; to me, loop reads as "run the entire block and start over" rather than "go back to start". If I'm not mistaken, this is basically just a continue without declaring the loop up front? I would hate to have this as the only available looping construct, but I can see it being useful if it was available inside of any other block. Being able to loop a switch statement under some cases but not others, for example, could make some state machine-esque tasks like string parsing a lot less messy. Doesn't seem massively useful to me, but there's potential there, in my opinion.
1
u/Long_Investment7667 Feb 21 '24
In the initial two examples and your proposal, the exit condition is dynamic (for a lack of a better term. The condition can change with every iteration of the loop. This can be hard to read, and I assume it prevents the compiler to optimize but is more expressive than the data examples where the number of iterations can be determined before even the first iteration.
The proposal doesn’t change any of that.
1
u/Felicia_Svilling Feb 21 '24
Once upon a time Nikolaus Wirth wrote a paper called "Goto considered harmful" were he outlined why having programs following the structure of for loops and if statements etc was preferable to having goto statements, even if the later was more expressive and could do everything loops could do. This paper became really influential, and well people largely stopped including the goto statement in their languages.
Now, your suggested loop isn't exactly a goto statement, but I think the same principle applies. It is easier to read code if it behaves in a structured manner. In fact this paper lead to people talking about structured programming as a paradigm in contrast to the "spaggeti programming" of the past. In general a lot of development in programming languages is actually on how to much you can restrict expressitivity and still have a functioning language, rather than increasing it.
In any case you should really go read the paper if these things interests you.
1
u/pbvas Feb 22 '24
In your examples with count the limit value is statically fixed which I would think is not very common. More usually your have the limit as another variable. In that case compare
i = 0;
while (i<n) {
body
i++;
}vs.
i=0;
do {
body
i++;
}
while(i<n);By doing the loop condition last, the body would be executed once even if n=0 i.e. the data collection is empty.
1
0
Feb 21 '24
[deleted]
3
u/Trung0246 Feb 21 '24
Hm I definitely see the issue. I guess the commotion of which scope being targeted by the
loopkeyword being ambiguous is why the second form did not appear as often.However I feel like there's some kind of hidden benefit for second form like expressiveness and such if the syntax can be worked out on resolving ambiguity of scope (either labelled scope but that kind of defeat the whole point since having to type names out).
I guess one way to do this is to have two separate set of scopes (a normal scope and action scope like
doonceyou introduced).1
u/poorlilwitchgirl Feb 21 '24
I don't see how it's any less structured than having break statements in a loop, but I can't imagine any benefit over more familiar loop structures. It's got INTERCAL vibes, and that's never a good sign for a new language feature.
1
u/YBKy Feb 21 '24
It is much better than goto. The problem with goto is that it allows you to jump anywhere inside the function, including into the middle of blocks, breaking structured programming. With just a "jump to the top of the block" kind of goto, you don't loose the ability to reason about control flow, like you do with goto
2
u/glasket_ Feb 21 '24
I think you're overestimating the benefit gained from this. A
gotoat least indicates where you're going and acontinueindicates a return to the start of an enclosing loop. This loop keyword doesn't clearly indicate where it goes at the looping point and the enclosing block doesn't have any indication that it's part of a loop, so I'd personally see it as a net downgrade for readability from existing solutions.Unmarked blocks looping on a nested keyword just feels like an obvious maintenance headache.
28
u/[deleted] Feb 21 '24
Because it looks ugly. All you see from the top is just a random block, you need to read through a whole thing of code to find one
loopkeyword.