-1

I need to create a loop, that in a first step something should be calculated and result of that calculation should be passed to test condition. It's something like:

do (something) while (condition)

It's mandatory, that first pass should make calculation just before test condition should occur.

Is it possible to do in Clojure?

I've found similar problem here on StackOverflow, but it was unclear for me. Those solutions presented here are much more precise.

Boba_Fett
  • 67
  • 2
  • 10

2 Answers2

2

Something like this, maybe:

(ns playground.core)

(defn do-while-loop [init-state do-something condition]
  (loop [state init-state]
    (let [next-state (do-something state)]
      (if (condition next-state)
        (recur next-state)
        next-state))))


playground.core> (do-while-loop 0 inc #(< % 6))
6
playground.core> (do-while-loop 0 inc #(< % 0))
1

init-state is the state you are looping on, do-something is a function to compute the next state, and condition is a function that returns a boolean value based on the state.

This is a purely functional do-while-loop with the condition being tested after the next state has been computed. And you can always add extra syntactic sugar on top of it using macros if you prefer that.

Rulle
  • 4,496
  • 1
  • 15
  • 21
1

I'd just use loop here. Whenever you can't decide how you want to loop, loop is a good starting point to feel things out since it's so general. A bare bones example would look like:

(loop []
  (let [result (some-calc)]
    (if (verify-result result) ; The condition
      (recur) ; Loop again
      result))) ; Or return the result of the calculation

Where some-calc is the producer, and verify-result checks if you should loop again.

You could even do away with the loop and use a recursive function:

(defn func []
  (let [result (some-calc)]
    (if (verify-result result)
      (recur)
      result)))
Carcigenicate
  • 43,494
  • 9
  • 68
  • 117