tags:

views:

99

answers:

3

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.

+1  A: 

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.

Ball
+2  A: 

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.

Tim Schaeffer
I did consider that. The comment says eval(g) never returns zero. The only cases where the second if block would be skipped is if either the comment lies (possible maybe even likely) or some_condition_satisfied(g) fails and the previous if block doesn't assign to a. So, I felt they could be joined.
Ball
+1  A: 

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))