user855
user855

Reputation: 19918

How to translate this piece of imperative code into Clojure code

Usually, we have situation like this in C++

int a=0;
if(some_condition_satisfied(g)) {
   a = eval(g);  // never returns 0
}
if(a!=0) {
  do_something();
}

How can I do the above in Clojure without using refs, because I cannot assign after initialization?

Thanks.

Upvotes: 0

Views: 281

Answers (3)

Hugo Duncan
Hugo Duncan

Reputation: 436

Assuming some_condition_satisfied is a predicate, your-eval-fn never returns false, and the value of a is required, you can also write:

(if-let [a (and (some-condition-satisfied? g)
                (your-eval-fn g))]
  (do-something a))

Upvotes: 1

Tim Schaeffer
Tim Schaeffer

Reputation: 2636

Try this:

(if-let [a (or (and (some-condition-satisfied g) 
                    (your-eval g))
               0)]
    (when (not= a 0)
       (do-something)))

Rembember that in clojure, 0 is true, not false, when used as a boolean, so some C idioms are lost in translation. I assume that the clojure version of some-condition-satisfied does not return a 0 to indicate false, but nil instead.

Ball: you forgot about the if(a!=0) part.

Upvotes: 2

Ball
Ball

Reputation: 2601

First, you can simplify the C++ to one block, if your comment is believed.

So, let's simplify in C++ first, shall we?

if(some_condition_satisfied(g)) {
  a = eval(g); // never returns zero, right?
               // so we roll the next if block into this one
  do_something();
}

In clojure, I'd try

(if (some_condition_satisfied g)
    (let [a (eval g)]
         (do_something)))

Notice I'm setting a a but not using it. Is that what you meant? Otherwise, pass it into do_something or change the if condition

(if (and (some_condition_satisfied g) (not= 0 (eval g)))
    (do_something))

This would match the C++ code for

if ( some_condition_satisfied(g) && 0 != eval(g) ){
  do_something();
}

Also, my clojure is rusty, but I'm pretty sure I checked the syntax.

Upvotes: 3

Related Questions