Josiah Kiehl
Josiah Kiehl

Reputation: 3633

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

Upvotes: 7

Views: 331

Answers (1)

sepp2k
sepp2k

Reputation: 370425

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.

Upvotes: 15

Related Questions