Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more lispy way to write this code?

I've been learning Clojure, and since I come from a Ruby, and before that Java background, I have trouble thinking procedurally.

Is there a more 'lispy' way to write this code, or is this ok?

(defn foo
  ([s t]
     (let [x (+ 4 (- t s))]
       (if (> 2 (if (> 6 x)
                  x
                  6)
              x)
         x
         2))))
like image 801
Josiah Kiehl Avatar asked Dec 20 '10 03:12

Josiah Kiehl


1 Answers

In clojure, like in any other language, it is usually best to use built-in functions whenever applicable. So since clojure has a min and a max function, so you can replace your ifs with:

(max 2 (min 6 x))

If those functions did not exist in clojure's standard library, I would have recommended defining them because putting the logic for min and max into their own function leads to much nicer code than having it all in the foo function.

like image 109
sepp2k Avatar answered Sep 22 '22 23:09

sepp2k