Neel
Neel

Reputation: 428

Evaluate an if expression and then return the same evaluation if false in Clojure

I want to evaluate a from in if binding of clojure and if it returns false then i want to return the evaluation.

For eg

(defn testa [testvalue](let [tval testvalue]
                    (assert (validate tval) "incorrectvalue")
                    (if (= (+ 4 tval) 8)
                      1
                      (+ 4 tval))))

So here validate is a function which validates some criteria but after that if expression results in false then i am returning the same result of the same expression i evaulated in if binding.But i want to avoid it writing again.

How can i do that?

Correction:- i also want to perform operation on tval before validate.

(defn testa [testvalue]
(let [tval (trim testvalue)] 
(assert (validate tval) "incorrectvalue") 
(if (= (+ 4 tval) 8) 
1 
(+ 4 tval))))

Thanks!!

Upvotes: 0

Views: 112

Answers (2)

leetwinski
leetwinski

Reputation: 17849

just for fun:

(defn testa [testvalue]
  (assert (validate testvalue) "incorrectvalue")
  (as-> (+ testvalue 4) v
        (if (== v 8) 1 v)))

in repl:

user=> (testa 10)
14
user=> (testa 4)
1

upd: updated according to op's comment to another answer.

let's say you prepare your testvalue somehow with the prepare function. Then the whole function may look like this:

(defn testa [testvalue]
  (as-> (prepare testvalue) v
        (do (assert (validate v) "incorrectvalue")
            v)
        (+ v 4)
        (if (== 8 v) 1 v)))

it works like this:

v = prepare(testvalue);
assert(validate(v), "incorrectvalue");
v = (+ v 4);
if (v == 8)
  return 1;
else
  return v;

Upvotes: 1

Frank C.
Frank C.

Reputation: 8096

Neal

I refactored and simplified to attain your desired result.

(defn testa [testvalue]
  (assert (validate testvalue) "incorrect value")
  (let [tval (+ 4 testvalue)]
    (if (= tval 8)
      1
      tval)))

Upvotes: 1

Related Questions