clojure.core/loop¶
Evaluates the exprs in a lexical context in which the symbols in the binding-forms are bound to their respective init-exprs or parts therein. Acts as a recur target.
Examples¶
Note by Jacolyte¶
"Acts as a recur target."
What's a recur target? A recurring target? A recursive target? I'm not a big fan of abbreviations or ambiguous terms.
Wouldn't it be awesome if a script could annotate all occurrences of glossary terms? Or automatically wrap glossary terms in anchor tags linking to their definition?
Note by devijvers¶
The problem loop is trying to solve is that recursively calling the same function on the JVM is expensive and doesn't scale. It might work if your data structure is a thousand levels deep but it will fail badly with a depth of millions of levels.
What is not possible on the JVM is what is called "tail-call optimization". loop is like a while loop in java, except that if you don't call recur (with the correct number of arguments) the loop will exit. In while-loop terms, recur avoids that a break statement is executed.
int counter = 0;
while (true) {
if (counter < 10) {
// recur
counter = inc(counter);
} else {
break;
}
}
In that sense loop is a recur target as in "target for recursion".
Note by Jacolyte¶
I wish the word recur in this document linked to the recur function. That'd be... awesome.
Note by zk¶
It really should (and will) show up in the 'vars in' section.
The problem is that recur is a special form, and is not parsed out correctly like other vars. This will be fixed in the future.
Note by Dimagog¶
Majority of loops that novices write can be expressed more elegantly using 3 fundamental functions map, filter and reduce. Or using list comprehension for.
Note by pmonks¶
To be clear, there's no technical reason the JVM can't support tail recursion (despite some complications to do with call stacks and security) - it just doesn't happen to support them currently.
People have been requesting this enhancement for at least a decade - here's one proposal, for example.
See also¶
- clojure.core/recur (9)
- clojure.core/trampoline (3)
- clojure.core/when (3)
- clojure.core/while (1)
- clojure.core/for (14)
- clojure.core/doseq (9)
- clojure.core/reduce (22)
- clojure.core/dotimes (1)
Content from the matching ClojureDocs page, with authors credited on each contribution.