Macro
Given a value and a list of template-expr clauses, evaluate the first expr whose template matches the value. There are four kinds of templates: 1) Lists of the form (tag x1 x2 ...) match instances of types whose constructor has the same form as the list. 2) Quoted lists of the form '(x1 x2 ...) match lists of the same length. 3) Vectors of the form [x1 x2 ...] match vectors of the same length. 4) Maps of the form {:key1 x1 :key2 x2 ...} match maps that have the same keys as the template, but which can have additional keys that are not part of the template. The values x1, x2, ... can be symbols or non-symbol values. Non-symbols must be equal to the corresponding values in the object to be matched. Symbols will be bound to the corresponding value in the object in the evaluation of expr. If the same symbol occurs more than once in a, template the corresponding elements of the object must be equal for the template to match.
; clojure/contrib/types.clj:240 (defmacro match [value & clauses] (when (odd? (count clauses)) (throw (Exception. "Odd number of elements in match expression"))) (let [vsymbol (gensym) cfsymbol (gensym) terms (mapcat (fn [[template expr]] (if (= template :else) [template expr] (let [[tests bindings] (tests-and-bindings template vsymbol cfsymbol)] [tests (if (empty? bindings) expr `(let ~bindings ~expr))]))) (partition 2 clauses))] `(let [~vsymbol ~value ~cfsymbol (constructor-form ~vsymbol)] (cond ~@terms))))
Copyright (c) Rich Hickey. All rights reserved.
The use and distribution terms for this software are covered by the Eclipse Public License 1.0, which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software.