view src/clojure/template.clj @ 10:ef7dbbd6452c

added clojure source goodness
author Robert McIntyre <rlm@mit.edu>
date Sat, 21 Aug 2010 06:25:44 -0400
parents
children
line wrap: on
line source
1 ; Copyright (c) Rich Hickey. All rights reserved.
2 ; The use and distribution terms for this software are covered by the
3 ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
4 ; which can be found in the file epl-v10.html at the root of this distribution.
5 ; By using this software in any fashion, you are agreeing to be bound by
6 ; the terms of this license.
7 ; You must not remove this notice, or any other, from this software.
9 ;;; template.clj - anonymous functions that pre-evaluate sub-expressions
11 ;; By Stuart Sierra
12 ;; June 23, 2009
14 ;; CHANGE LOG
15 ;;
16 ;; June 23, 2009: complete rewrite, eliminated _1,_2,... argument
17 ;; syntax
18 ;;
19 ;; January 20, 2009: added "template?" and checks for valid template
20 ;; expressions.
21 ;;
22 ;; December 15, 2008: first version
25 (ns ^{:doc "Macros that expand to repeated copies of a template expression."
26 :author "Stuart Sierra"}
27 clojure.template
28 (:require [clojure.walk :as walk]))
30 (defn apply-template
31 "For use in macros. argv is an argument list, as in defn. expr is
32 a quoted expression using the symbols in argv. values is a sequence
33 of values to be used for the arguments.
35 apply-template will recursively replace argument symbols in expr
36 with their corresponding values, returning a modified expr.
38 Example: (apply-template '[x] '(+ x x) '[2])
39 ;=> (+ 2 2)"
40 [argv expr values]
41 (assert (vector? argv))
42 (assert (every? symbol? argv))
43 (walk/prewalk-replace (zipmap argv values) expr))
45 (defmacro do-template
46 "Repeatedly copies expr (in a do block) for each group of arguments
47 in values. values are automatically partitioned by the number of
48 arguments in argv, an argument vector as in defn.
50 Example: (macroexpand '(do-template [x y] (+ y x) 2 4 3 5))
51 ;=> (do (+ 4 2) (+ 5 3))"
52 [argv expr & values]
53 (let [c (count argv)]
54 `(do ~@(map (fn [a] (apply-template argv expr a))
55 (partition c values)))))