Reputation: 49329
What is the idiomatic way to create an infinite loop?
while(true){
calc();
}
I want to call the calc function forever. Only one function is called over and over again.
EDIT: One other thing I forgot to mention is that calc has side effects. It does some calculations and modifies a byte array.
Upvotes: 21
Views: 9872
Reputation: 2028
Another solution would be to use repeatedly
like:
(repeatedly calc)
Rather than an infinte loop, this returns an infinite sequence. The lazy sequence will be a little slower than a tight loop but allows for some control of the loop as well.
Upvotes: 3
Reputation: 19632
Using the while
macro that Brian provides in his answer it is a simple task to write a forever
macro that does nothing but drops the boolean test from while
:
(defmacro forever [& body] `(while true ~@body)) user=> (forever (print "hi ")) hi hi hi hi hi hi hi hi hi hi hi ....
This is the fun part of any Lisp, you can make your own control structures and in return you avoid a lot of boilerplate code.
Upvotes: 17
Reputation: 72926
while
is in the core libraries.
(while true (calc))
This expands to a simple recur
.
(defmacro while
"Repeatedly executes body while test expression is true. Presumes
some side-effect will cause test to become false/nil. Returns nil"
[test & body]
`(loop []
(when ~test
~@body
(recur))))
Upvotes: 28