Quantcast
Channel: Community Center - ClojureVerse
Viewing all articles
Browse latest Browse all 169

Multimethods, establishing priority of which gets called

$
0
0

I get this error:

Unable to resolve symbol: _ in this context

Apparently I can use _ as an argument to a function but not as a dispatch value. Is there any dispatch value I can use that means “I don’t care what value is in this spot”?

Assume I have this, which plays a big role in determining how I handle a JSON blob that has just arrived at my app:

 (defmulti make-choice (fn [params]
                        [
                         (get params :choice)
                         (true? (get params :item-id))
                         (allowed-item-type? (get params :item-type))
                         (true? (get params :page))
                         (number? (get params :page))
                         ]
                        ))

The second and third parameters are mutually exclusive, so I want something like this:

     (defmethod make-choice [_ true true _] [params]
      {:method (str "Error: your request had both item-id and item-type but they are mutually exclusive. " params)})

My question: is there a way I can get this to take priority over all other methods of this multi? That is, no matter what other combinations exist, if these two parameters are true, then this make-choice is triggered? Does it happen automatically or do I have to worry about something else happening?

I’d like to put all of my possible error states together like this:

(defmethod make-choice :default [params]
  {:message (str "We were unable to find that page or choice:" params)})

(defmethod make-choice [_ true true _ _] [params]
  {:method (str "Error: your request had both item-id and item-type but they are mutually exclusive. " params)})

(defmethod make-choice [_ true _ true _] [params]
  {:method (str "Error: your request had both item-id and a page parameter but they are mutually exclusive. " params)})

(defmethod make-choice [_ _ _ true true] [params]
  {:method (str "Error: your request had a page parameter but it was not an integer. " params)})

But can I be sure that these error states will always take precedence over any other combination of parameters that get sent to make-choice?

5 posts - 4 participants

Read full topic


Viewing all articles
Browse latest Browse all 169

Trending Articles