Sam Moore
Sam Moore

Reputation: 11

Clojure - If based on Some result

I want to start this post with an apology, I am entirely self tought and this is my first question, though I use Stackoverflow A LOT.

I want to make a decision based on the result of a some function...

(if (= nil (some (partial = (:activeboard (:boards app)))
                 (:otherboards (:boards app))))
  (om/transact! (:boards app) :activeboard (fn [_] active)))

I know the some test works as I have the same some function further down to output the result to the screen. But the if test does not. I have similarly tried a case and a condp. Nothing seems to evaluate the some function. The result of the some function is either nil, or true, so if should evaluate that??

Upvotes: 1

Views: 92

Answers (2)

jas
jas

Reputation: 10865

There's nothing special about evaluating some within if and as far as I can tell your code is fine. Take a look below and see if you can construct something similar (that we can all try running ourselves) and that demonstrates the problem.

Case 1, activeboard is included in otherboard:

(def app {:boards {:activeboard 1 :otherboards [1 2 3]}})

(if (= nil (some (partial = (:activeboard (:boards app))) (:otherboards (:boards app))))
  (println "some returned nil")
  (println "some did not return nil"))

evaluated:

>> some did not return nil

Case 2, activeboard is not included in otherboard:

(def app {:boards {:activeboard 1 :otherboards [2 3 4]}})

(if (= nil (some (partial = (:activeboard (:boards app))) (:otherboards (:boards app))))
  (println "some returned nil")
  (println "some did not return nil"))

evaluated:

>> some returned nil

Upvotes: 1

Joshua
Joshua

Reputation: 2982

First, code indentation can go a long way in helping you to understand your own code. I edited your question to be at least a bit more clear.

Second, consider using the thread-first operator (->) or get-in to navigate through multiple levels in a map. But that's merely a code style thing.

Your condition looks fine, just as @jas already demonstrated. What could get you into trouble is that you do not provide an "else" path to your if. The if macro expects three "parameters": the condition, the "then" block and the "else" block. If you only want to test the truthy case of your condition, use when.

Hope that helped.

Upvotes: 1

Related Questions