[ACCEPTED]-Clojure infinite loop-clojure

Accepted answer
Score: 28

while is in the core libraries.

(while true (calc))

This expands to 1 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
Score: 17

Using the while macro that Brian provides in his answer 5 it is a simple task to write a forever macro that 4 does nothing but drops the boolean test 3 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 2 can make your own control structures and 1 in return you avoid a lot of boilerplate code.

Score: 13

(loop [] (calc) (recur))


Score: 3

Another solution would be to use repeatedly like:

(repeatedly calc)

Rather 4 than an infinte loop, this returns an infinite 3 sequence. The lazy sequence will be a little 2 slower than a tight loop but allows for 1 some control of the loop as well.

More Related questions