开发者

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.


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.


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜