TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

What if you couldn’t program with loops?

87 点作者 helloiloveyou将近 6 年前

35 条评论

pcstl将近 6 年前
While the article is a cute way to introduce the loop body extraction refactoring, I think it is a disservice to talk about not using loops without mentioning recursion.<p>I am quite often shocked at the number of programmers who, even after years of experience, are not able to use recursion properly. (Not saying this is true of the article&#x27;s author - but they should have mentioned recursion)
评论 #20441151 未加载
评论 #20441458 未加载
评论 #20441399 未加载
评论 #20440383 未加载
评论 #20441908 未加载
评论 #20440659 未加载
dig1将近 6 年前
In Scheme, the only way to loop is via recursion. In Clojure, all high level functions and looping macros (for&#x2F;doseq) are implemented via recursion as well (loop&#x2F;recur).<p>Yes, it requires significant paradigm shift when you start to use these languages, but after a while, you start to appreciate high level functions (map, reduce) instead of language looping constructs (for, while) - they can be easily composed, parallelized, scaled over cluster, refactored... Even code looks much cleaner.<p>You like it even more if you are mathematician, because things looks more &quot;natural&quot; :D
评论 #20440086 未加载
评论 #20439228 未加载
评论 #20439174 未加载
评论 #20439362 未加载
评论 #20443607 未加载
评论 #20440581 未加载
lincpa将近 6 年前
In the pure function pipeline data flow, no loop is required.<p>I wrote a 100k lines of pure clojure language project, no loop is used, and tail recursion is only used once. Most of them use high-order functions for dataflow processing or data driving.<p>[The Pure Function Pipeline Data Flow](<a href="https:&#x2F;&#x2F;github.com&#x2F;linpengcheng&#x2F;PurefunctionPipelineDataflow" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;linpengcheng&#x2F;PurefunctionPipelineDataflow</a>)
评论 #20444221 未加载
sk5t将近 6 年前
So, I was sort of expecting this article to use recursion instead of a regular loop, but it was not to be, as the author went ahead and used a for-loop anyway and abstracted a bit of logic into a separate function. Silly premise overall.
评论 #20438687 未加载
评论 #20438142 未加载
评论 #20438062 未加载
评论 #20438082 未加载
评论 #20438190 未加载
评论 #20438660 未加载
评论 #20438672 未加载
whatshisface将近 6 年前
Everyone in this comment section was expecting some kind of programming language trickery, but that&#x27;s not what this post is about. The author is illustrating a refactoring technique.
评论 #20439326 未加载
molticrystal将近 6 年前
I was thinking it would be an essay on computational completeness and memory or functionality without the ability to loop, which is as fundamental as moving the tape head left or right on a Turing machine. I suppose the title of the article overly encourages what one might interpret it to be about. The upvotes and comments here provide evidence that the article is useful, just not what everybody might be expecting.
diego将近 6 年前
I&#x27;d use functional programming, which is what I&#x27;d thought this post would be about. It seems the author is not familiar with the concepts of mapping, reducing and filtering. This is just a map() command.
评论 #20439074 未加载
deanCommie将近 6 年前
It&#x27;s really hard to teach clean code to beginners.<p>Concepts like SOLID principles feel like meta-academic overkill, and get in the way of &quot;getting things done&quot;.<p>Juniors don&#x27;t click in to the value of well structured well modularized code until they handle the pain of refactoring code that isn&#x27;t, and introducing unintentional bugs into it.<p>Your only hope, as a senior engineer, who&#x27;s been through it already, is that they have enough trust in you that when you leave code review feedback that says &quot;It would be more clear and maintainable if you refactor that into a function&#x2F;make the function return the value instead of mutating it as a side effect&#x2F;etc etc etc&quot; they trust you, even if they don&#x27;t yet feel the real value of it)<p>I can&#x27;t tell if this blog post helps or not. I need to ask one of my juniors.
评论 #20438876 未加载
rthomas6将近 6 年前
Functional programming is the answer. In python the answer is just this:<p><pre><code> def action(thing) ... map(action, array_of_things) </code></pre> I&#x27;m sure there&#x27;s some similar solution in Javascript.
评论 #20442609 未加载
评论 #20442145 未加载
评论 #20441318 未加载
评论 #20441394 未加载
regecks将近 6 年前
There are real life situations where you must program without loops, and eBPF programs are an example. They also have an program size and various other limitations (<a href="http:&#x2F;&#x2F;www.brendangregg.com&#x2F;ebpf.html#bccprogramming" rel="nofollow">http:&#x2F;&#x2F;www.brendangregg.com&#x2F;ebpf.html#bccprogramming</a>).<p>When I was writing an ACME (Let&#x27;s Encrypt) TLS-ALPN client that ran in-kernel with an eBPF tc program, it led to some pretty silly looking code: <a href="https:&#x2F;&#x2F;dpaste.de&#x2F;82aZ" rel="nofollow">https:&#x2F;&#x2F;dpaste.de&#x2F;82aZ</a>
KhoomeiK将近 6 年前
This is sort of what Microsoft&#x27;s new&#x2F;experimental Bosque language is supposed to be about—a paradigm shift to &quot;Regularized Programming&quot;, similar to the advent of Structured Programming in the 1960&#x27;s.<p>Here&#x27;s the paper: <a href="https:&#x2F;&#x2F;www.microsoft.com&#x2F;en-us&#x2F;research&#x2F;uploads&#x2F;prod&#x2F;2019&#x2F;04&#x2F;beyond_structured_report_v2.pdf" rel="nofollow">https:&#x2F;&#x2F;www.microsoft.com&#x2F;en-us&#x2F;research&#x2F;uploads&#x2F;prod&#x2F;2019&#x2F;0...</a>
alecmg将近 6 年前
Just recently was rminding myself good numpy practices and honestly thought this was also an article about broadcasting and vectorization.<p>Look Ma, No For-Loops: Array Programming With NumPy <a href="https:&#x2F;&#x2F;realpython.com&#x2F;numpy-array-programming&#x2F;" rel="nofollow">https:&#x2F;&#x2F;realpython.com&#x2F;numpy-array-programming&#x2F;</a><p>Which is powerful and enables multicore execution even on notorious Python GIL
fouc将近 6 年前
It ends up being a form of mapping. It&#x27;s a good idea&#x2F;exercise for developers to engage in occasionally in order to improve their ideas on how to organize their code.
评论 #20438188 未加载
robomartin将近 6 年前
At the risk of inspiring a violent reaction (virtually, of course): Sorry folks, this is silly. Go solve real problems.<p>Does a patient care if the ML code that discovered a malignant tumor used an explicitly written loop?<p>As a silly test: What would be the value in rewriting the Facebook, Google, Amazon, etc. codebases to avoid loops? What’s the ROI?<p>Kindly provide a few examples at scale (not academic oddities) where this might actually matter?<p>You can’t avoid loops. Any time you are doing the same thing repeatedly, you are using a loop, whether you explicitly wrote it or not.<p>Sure, sure, there are corner cases. I have unrolled loops in assembly in real time embedded code where every microsecond counted. That is far from the norm and, frankly, should be avoided with absolute passion.<p>I have also worked with APL for ten years. You can do amazing things with the language while seemingly not looping. In reality nearly everything you do with APL includes heavy looping behind the curtains, and you better be well aware of this if performance is important.<p>Don’t get me wrong, the academic question is interesting. However, if you live and work in the real world there are far more interesting and pressing issues to be concerned with.
lalos将近 6 年前
I could see this as an effective pedagogical tool when learning to program.
评论 #20438105 未加载
patrickhogan1将近 6 年前
The example calls indexOf instead of calling a loop directly and indexOf uses a loop under the hood.<p><a href="https:&#x2F;&#x2F;developer.mozilla.org&#x2F;en-US&#x2F;docs&#x2F;Web&#x2F;JavaScript&#x2F;Reference&#x2F;Global_Objects&#x2F;Array&#x2F;indexOf" rel="nofollow">https:&#x2F;&#x2F;developer.mozilla.org&#x2F;en-US&#x2F;docs&#x2F;Web&#x2F;JavaScript&#x2F;Refe...</a>
评论 #20438492 未加载
glangdale将近 6 年前
A strange emphasis. I imagined old-school GPGPU (only with loops with fixed bounds).<p>Programming without branches of any kind (loop branches or otherwise) is a fun diversion; I&#x27;ve enjoyed it sufficiently to have put my blog at branchfree.org - will be more on branch free programming when my superoptimizer is more mature.
taffer将近 6 年前
Since no one has mentioned SQL yet:<p><pre><code> SELECT * FROM products WHERE (stock &gt; 100 AND price &lt; 5) OR (price BETWEEN 20 AND 35 AND category = &#x27;outdoors&#x27;) OR name ILIKE &#x27;%mountain%&#x27;;</code></pre>
harimau777将近 6 年前
I primarily program in JavaScript and between Lodash and the built in iterator functions I don&#x27;t see any reason to use loops other than the while loop.<p>I often use recursion rather than while loops; however, I find that is often difficult to do in a way that is readable and that uses tail recursion.<p>What I really wish is that something like &quot;forUntil&quot;, &quot;mapUntil&quot;, and &quot;reduceUntil&quot; would be added to the core language. Maybe the forEach, map, and reduce could be made generic functions that operated on any iterable rather than being defined as methods of Array.
Agentlien将近 6 年前
The title of this article reminded me of that one time when I found a small programming app for android with a very limited language. It had some basic variables, if statements and a drawing routine for solid colour circles. It contained no function calls and I don&#x27;t think it allowed for loops.<p>What it did have was timers which took a piece of callback code and could be set to repeat that code with a given frequency.<p>It was all very simplistic and restricted, so I spent an evening making a breakout clone in it, just to see if I could. That was a lot of frustrating fun.
leshow将近 6 年前
I really thought the blog post would end with recursion, and found no mention of it anywhere.
jchw将近 6 年前
I was sort of wondering if the conclusion would be to use map&#x2F;filter&#x2F;etc, but instead... it was to use an ordinary loop.<p>I am aware that there is a programming practice for writing “branchless” code. I was expecting this to be more along those lines.
评论 #20438209 未加载
Mugwort将近 6 年前
I have a much harder time reasoning with loops than using map, reduce, recursion etc. I&#x27;ll just say the whole truth, I can&#x27;t program with loops, I get a headache and I&#x27;m forced to quit.
ChrisSD将近 6 年前
Use Rust&#x27;s `const fn`. In its current state you can&#x27;t do any looping, Nor any other control flow. Fun times.<p>Doing recursion works easily enough but the hard part is stopping.
thb567将近 6 年前
You could just get the thing going running an external file&#x2F;script. And stop it with an if condition. It&#x27;s a classic structure from very noob admins.
zadkey将近 6 年前
I think you would just use recursion to implement loops.
vincent-toups将近 6 年前
No stinking loops link: <a href="http:&#x2F;&#x2F;nsl.com&#x2F;" rel="nofollow">http:&#x2F;&#x2F;nsl.com&#x2F;</a>
pmlnr将近 6 年前
If you program in C, try MISRA C and it&#x27;s requirements&#x2F;restrictions.
hkai将近 6 年前
In fact, you can set up an eslint rule banning any loops from your code.
cozzyd将近 6 年前
Kind of like matlab or numpy? (If you don&#x27;t want it to be super slow).
fvilers将近 6 年前
Not that hard, a loop is just an &quot;if&quot; and a &quot;jump&quot; instructions.
cr0sh将近 6 年前
As an alternative, what if you didn&#x27;t have (or didn&#x27;t want to use) common structured programming techniques, and you wanted to implement a state machine? Like, you could use if-then, but not while, loop, do, etc? But goto was allowed (argh?).<p>About a decade ago I was in a discussion with someone on this, and his technique changed my mind on where, when, and how goto could be acceptable in a real code base; some of you may or may not agree - but I thought I would show you, warts (on my part) and all. Here&#x27;s the thread:<p><a href="https:&#x2F;&#x2F;www.electro-tech-online.com&#x2F;threads&#x2F;state-machine-in-mcu.113718&#x2F;" rel="nofollow">https:&#x2F;&#x2F;www.electro-tech-online.com&#x2F;threads&#x2F;state-machine-in...</a><p>...also, here&#x27;s the state machine (as implemented in C); the original post of the image on the forum, I think, requires a login to see, thus this copy:<p><a href="http:&#x2F;&#x2F;i.imgur.com&#x2F;JkND1Av.png" rel="nofollow">http:&#x2F;&#x2F;i.imgur.com&#x2F;JkND1Av.png</a><p>Read the thread to understand the arguments for and against, but it ultimately (I think) comes down to implementation readability and maintainability. This is a more critical thing in an embedded hardware system, of course, but I think similar techniques, or at least the mindset behind them, could be an advantage.<p>It&#x27;s kinda like how learning Golang, much later, forced me to rethink the idea of error handling. In Go, there&#x27;s the concept of using &quot;guard statements&quot; at the top of functions&#x2F;methods to essentially exit out as soon as possible if something untoward occurs or is passed as an argument incorrectly. Basically a bunch of simple if-then statements at the beginning, then your code proper. It was one of those things I recall as being something I railed against at first, but I quickly came to understand the reasoning behind doing it that way, rather than nested if-then statements or other constructs within the logic. It produced simpler, easier to follow code - but at first, it felt very &quot;wrong&quot; to me for some reason. It was one of many &quot;golang-isms&quot; I had to come to terms with, before I really appreciated the whys and whats of the language.<p>Which ultimately is what these techniques are all about - the author touches upon this: Restriction of your toolset can lead to fascinating solutions, and in some or many cases, this simplification is reflected in the code as well; things can become easier to understand, since less is being used. It&#x27;s also one of the reasonings behind such &quot;demo competition&quot; contests such as the 256 byte challenge, or 1K intros, etc. Also behind such things as pixel-art, especially tile art using only 8 colors (or even just black and white!) with only an 8 x 8 grid-space to work in. Some amazing art comes out of that, operating within such restrictions.<p>I&#x27;ve heard&#x2F;read that great programmers are those who are able to remove more code than they add for a given change (aka - simplifying the code). These techniques and everything else may all be a part of that idea.
cr0sh将近 6 年前
IIRC, Mel, The Real Programmer, didn&#x27;t need loops...<p><a href="https:&#x2F;&#x2F;news.ycombinator.com&#x2F;item?id=9913835" rel="nofollow">https:&#x2F;&#x2F;news.ycombinator.com&#x2F;item?id=9913835</a><p>---<p>I&#x27;m going to expand on this - the author of the article doesn&#x27;t mention a couple of things that you can do if you don&#x27;t use loops, or don&#x27;t have them for some reason, but it is understandable that it wasn&#x27;t mentioned - because the author is working in javascript, not in something lower level.<p>However, that may change with WASM coming into its own; depending on if anyone takes the challenge up of hand coding WASM (that actually isn&#x27;t an &quot;if&quot; - I am certain people are doing it as I type this).<p>Those two commonly known (well, used to be - less so today, maybe, outside of embedded programmers of 8 and 16 bit controllers - and the retro and demo scene) methods:<p>1. Self-modifying code<p>2. Overflows<p>Number 2 could be seen as a subset of number 1, depending on how an overflow is exploited.<p>It&#x27;s been decades since I&#x27;ve played with either of them - and really only at a &quot;toy&quot; level, but they were common techniques for those well versed in assembler (for whatever processor or architecture), as they could be used to write both more efficient and smaller code for a given routine.<p>Especially in the old 8-bit realm and before, when memory was precious and expensive, and not very large, such techniques could allow for more functionality than what might seemingly fit into memory space available. They were used for everything, particular games on 8-bit machines, as well as more mundane software.<p>The downside is that the code created was often very &quot;opaque&quot; in the sense that you really had to understand how potentially the whole system was working in order to understand how the technique worked and was being used in context. This worked to the advantage of some developers - namely those writing old-school viruses&#x2F;trojans&#x2F;malware - as the ability to have self-modifying code meant they could easily hide themselves from a malware detector, and do other nefarious (and honest, sometimes quite interesting) techniques. It&#x27;s less a thing today, but back in the day, there were some amazing bits of code floating around that scene.<p>The guy who wrote about Mel understood all this - or came to understand it - very well. Mel did it mainly because he didn&#x27;t trust compilers to make fast code (which they probably didn&#x27;t back in his day - even today, there are edge cases that fall thru the cracks - it&#x27;s just code, it can&#x27;t do everything - yet) - so he hand coded everything; he also had the advantage that he knew precisely how the system worked, especially the drum memory of that system, and by precisely timing things, and deft use (abuse?) of certain registers - well, he was able to do seemingly wizard-like tasks. I can&#x27;t say he didn&#x27;t use any loops - he did in fact use one; it looked like an endless loop with nothing inside it; in fact, it should just cause the machine to hang. But the author of Mel&#x27;s story found that the machine, stepping through the code, would pass right thru this seemingly endless loop. Well - he explains how Mel did it, and it really is a thing of wonder, combining both register manipulation, overflow techniques, and self-modifying code to the utmost.<p>Read the story to find out more (Mel - as far as can be determined, was likely a real person; there is a picture of him out there that was dug up. No one knows for certain whether that Mel is The Mel - but most believe the person depicted probably is).<p>Also google around on such techniques to learn how they work; you likely won&#x27;t be able to apply them to your day-to-day (unless you work in assembler or something like that), but you might learn something useful for your toolbag.<p>Oh - one other thing - I kinda lied about how these tricks can only apply to a low-level; that&#x27;s not completely true. There are certain techniques that can be done with higher level languages (and not using exploitable bugs). I won&#x27;t go into detail here, though. Maybe you can work it out on your own?
exabrial将近 6 年前
Why not though? Generally our CPUs are based around jumps
评论 #20438195 未加载
yjhoney将近 6 年前
I teach a JS coding class and I had the luxury of creating the curriculum. To the horror of my peers, I decided that coding with loops was not necessary for beginners and got rid of loops altogether from our curriculum. I thought OP was proposing the same thing, but I was wrong. the refactoring was good, but my students will probably end up with the following result (more in line with your no loops title):<p>```<p>function highlightProducts(aListOfProducts, i=0){<p><pre><code> if (i === aListOfProducts.length) return null if(productShouldBeHighlighted(product)){ product.highlighted = true } return highlightProducts(aListOfProducts, i + 1) </code></pre> }<p>```<p>The added benefit of the above approach is that debugging is easier! If you want to debug the last 5 items, you can simply call the function like this:<p>highlightProducts(aListOfProducts, aListOfProducts.length – 5)<p>Ultimately, though, everyone should be using higher order functions (map, reduce filter, find, etc.)
评论 #20439186 未加载
评论 #20438463 未加载
评论 #20438272 未加载
评论 #20438534 未加载