Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting the Java concept into Clojure

Tags:

java

clojure

I am pretty new with Clojure. I have one Java method including a boolean variable and I want to rewrite this method to use it with the same functional in Clojure as well. But I couldn't find how to set the boolean value true and false in run-time in Clojure.

The following snippet basically emphasize only the boolean part, It is difficult to think for me to write this in a functional way.

int calculate(...){
  int y = 0;
  boolean flag = false;
  foreach(...){
     if(!flag){
        y = 1;
        flag = true;
     }
     else{
        y = -1;
        flag = false;
     }
  }
  return y;
} 

Here is the my first attempt in Clojure:

(defn calculate [...]
    ( ??flag?? -> I do not know which macro I should use over here
      (doseq [x ...]
        (if (false? flag) (do 1 (set the flag true)) 
           (do -1 (set the flag false)))))

How can I implement the same concept in Clojure?

like image 266
Hakan Özler Avatar asked Jun 11 '26 09:06

Hakan Özler


1 Answers

For the Java code you have, it looks like the simplest way to translate it into Clojure would be to skip all the iterating and just return the final value:

(defn calculate [coll]
  (odd? (count coll)))

If you want something more elaborate I guess you could do something like

(defn calc [coll flag]
  (if (empty? coll)
    flag
    (recur (rest coll) (not flag))))

and call it with

(defn calculate [coll]
  (calc coll false))     

This kind of recursion isn't the most idiomatic style, and it's kind of crazy for this problem, but it demonstrates how instead of mutating variables you write an expression that when evaluated produces the value passed into the next iteration (see the recur call in the example above).

It would be better style to rewrite this like

(defn calculate
  ([coll flag]
    (if (empty? coll)
      flag
      (recur (rest coll) (not flag))))
  ([coll]
    (calculate coll false)))

so there's only one function name to deal with. (I left the other way in thinking it would likely be clearer to read for somebody new to Clojure.)

I second the comment suggesting you look at 4clojure. It's a good way to get practice, and once you have a solution you can learn from what other users did.

like image 172
Nathan Hughes Avatar answered Jun 13 '26 05:06

Nathan Hughes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!