Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Predicate dispatch is a way of providing different responses to a function call, based on the number, "shape" and values of the arguments to the function. Clojure functions already dispatch to different bodies of code, depending on the number of arguments passed to the function:</p> <pre><code>(defn my-func ([a] (* a a)) ([a b] (* a b))) </code></pre> <p>Clojure multimethods add to this the ability to dispatch to different methods—perhaps defined in different namespaces—based on the return value of a dispatch function that examines the arguments (which can include their number, class, and value) and identifies which method to all. As noted in the footnotes to Stuart Sierra's answer, the creator of the multimethod gets to define the dispatch function, and it can't ordinarily be modified. Also, the programmer has to hand-design an ultra-complex dispatch function for a function that executes one thing for an integer of value 0, and another for a positive integer; or one thing for a list of one or more items, and another for an empty list.</p> <p>Predicate dispatch would (perhaps) provide a syntax that generated this complex dispatch function itself. For example, a factorial function could be defined this way</p> <pre><code>(defmatch fact [0] 1) (defmatch fact [n] (* n (fact (dec n)))) </code></pre> <p>The former code responds to a call to</p> <pre><code>(fact 0) </code></pre> <p>the latter code to a call with a single argument of any other value. This would (behind the scenes) define a multimethod with a dispatch function that distinguishes the zero from other values.</p> <p>But later I could specify that I want a factorial for a map (perhaps) by coding</p> <pre><code>(defmatch fact [x {}] (fact (:value x))) </code></pre> <p>and the code could (in theory) intercept calls passing a map to fact, delegating other calls to the original dispatch function...all behind the scenes.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload