Hamza Yerlikaya
Hamza Yerlikaya

Reputation: 49329

Clojure infinite loop

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

Answers (4)

M Smith
M Smith

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

Jonas
Jonas

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

Brian Carper
Brian Carper

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

Mark Bolusmjak
Mark Bolusmjak

Reputation: 24399

(loop [] (calc) (recur))

Upvotes: 14

Related Questions