You're viewing version 1.2.0 of defmacro. The latest stable version of Clojure Core is 1.3.0.
1.2.0 Arrow_down_16x16

defmacro

clojure.core

  • (defmacro name doc-string? attr-map? [params*] body)
  • (defmacro name doc-string? attr-map? ([params*] body) + attr-map?)
Like defn, but the resulting function name is declared as a
macro and will be used as a macro by the compiler when it is
called.

3 Examples top

  • (defmacro with-tree [tree & body]
      "works on a JTree and restores its expanded paths after executing body"
      `(let [tree# ~tree
             root# (.getRoot (.getModel tree#))
             expanded# (if-let [x# (.getExpandedDescendants
                                    tree# (TreePath. root#))]
                         (enumeration-seq x#)
                         ())
             selectionpaths# (. selectionmodel# getSelectionPaths)]
         ~@body
         (doseq [path# expanded#]
           (.expandPath tree# path#))))
    
    ;; usage:
    
    (with-tree *one-jtree-instance*
       ;; some code here...
      )
  • (defmacro unless [pred a b]
      `(if (not ~pred) ~a ~b))
    
    ;; usage:
    
    (unless false (println "Will print") (println "Will not print"))
  • (def dbg 1)
    
    (defmacro chk-flagM
      "Throws an exception if flag does not resolve; else returns flag's value."
      [flag]
      (if (not (resolve flag))
        (throw (Exception. (str 'flag " is not a valid var.")))
        flag))
    
    (defn write-csv-file
      "Writes a csv file using a key and an s-o-s"
      [out-sos out-file]
    
      (if (>= (chk-flagM dbg) 2)
        (println (first out-sos), "\n", out-file))
    
      (spit out-file "" :append false)
      (with-open [out-data (io/writer out-file)]
          (csv/write-csv out-data (map #(concat % [""]) out-sos))))
    
    
Log in to add / edit an example.

See Also top

Log in to add a see also.

Plus_12x12 Minus_12x12 Source clojure/core.clj:370 top

(def

 ^{:doc "Like defn, but the resulting function name is declared as a
  macro and will be used as a macro by the compiler when it is
  called."
   :arglists '([name doc-string? attr-map? [params*] body]
                 [name doc-string? attr-map? ([params*] body)+ attr-map?])
   :added "1.0"}
 defmacro (fn [&form &env 
                name & args]
             (let [prefix (loop [p (list name) args args]
                            (let [f (first args)]
                              (if (string? f)
                                (recur (cons f p) (next args))
                                (if (map? f)
                                  (recur (cons f p) (next args))
                                  p))))
                   fdecl (loop [fd args]
                           (if (string? (first fd))
                             (recur (next fd))
                             (if (map? (first fd))
                               (recur (next fd))
                               fd)))
                   fdecl (if (vector? (first fdecl))
                           (list fdecl)
                           fdecl)
                   add-implicit-args (fn [fd]
                             (let [args (first fd)]
                               (cons (vec (cons '&form (cons '&env args))) (next fd))))
                   add-args (fn [acc ds]
                              (if (nil? ds)
                                acc
                                (let [d (first ds)]
                                  (if (map? d)
                                    (conj acc d)
                                    (recur (conj acc (add-implicit-args d)) (next ds))))))
                   fdecl (seq (add-args [] fdecl))
                   decl (loop [p prefix d fdecl]
                          (if p
                            (recur (next p) (cons (first p) d))
                            d))]
               (list 'do
                     (cons `defn decl)
                     (list '. (list 'var name) '(setMacro))
                     (list 'var name)))))
Vars in clojure.core/defmacro: cons fn let list name defn
Used in 370 other vars (expand)
bound-fn time doseq if-not letfn for cond fn dosync with-open gen-interface sync let dotimes defmethod lazy-cat defstruct with-in-str loop import defrecord with-out-str when-not ->> refer-clojure .. with-loading-context future doto proxy-super assert memfn when-first definline defn- pvalues comment ns with-precision extend-type or condp with-local-vars with-bindings when-let amap -> while case deftype if-let extend-protocol and declare locking definterface delay defmulti proxy reify gen-class defonce io! lazy-seq when areduce defprotocol binding doc emit-array-impls with-sh-dir with-sh-env with-bindings formatter-out formatter pp with-pprint-dispatch pprint-logical-block source dir do-template deftest- deftest is testing try-expr are with-test-out set-test with-test with-junit-output with-tap-output defmacro- deftype defvar- defvar capture-and-send apply-macro with-command-line cond-let raise handler-case defunbound- defn-memo defhinted defunbound defonce- defalias defnk defstruct- cell ?- <- make-database trace-datalog with-in-reader with-out-append-writer with-out-writer deferror throw-msg continue continue-with with-handler do-not-handle raise fcase re-case case in-case instance-case source run defadt defmethod* qsym import-static with-in-reader with-out-append-writer with-out-writer with-system-properties with-connection formatter-out info log trace error spy with-logs warn enabled? debug fatal macrolet deftemplate defsymbolmacro with-symbol-macros symbol-macrolet with-direct-linking const letfn- lazy-get vars times dir has-args expect docs with-monad domonad defmonad m-when-not m-when monad monad-transformer defmonadfn m-lift formatter prlabel pp with-pprint-dispatch pprint-logical-block defstream with-profile-data profile prof with-system-properties rec-seq rec-cat rec-seq rec-cat with-sh-dir with-sh-env with-sh-dir with-sh-env with-query-results transaction with-connection docodepoints dochars deftype- defst docodepoints dochars << do-swing do-swing-and-wait deftest- do-template deftest is testing try-expr are with-test-out set-test with-test dotrace deftrace match with-ns with-temp-ns defservice time-series-plot box-plot add-box-plot add-categories stacked-bar-chart bar-chart heat-map xy-plot pie-chart scatter-plot dynamic-scatter-plot line-chart function-plot add-points histogram sliders add-function add-lines stacked-area-chart area-chart dynamic-xy-plot add-histogram $= combine-with $fn with-data transform-with formula with-rotation sketch with-translation deriv-fn deriv reset define-ant-task has-run? define-ant-type deftarget define-all-ant-tasks defproject describe testing-fn for-these it should defconfig describe defn! times has-args expect fail for-these collection-generator char-generator for-all generator testing-fn it with-timing debug-repl local-bindings should given and when then wtf with-re-defn local-bindings strict-mode transform-content deftemplate snippet* defsnippets template defsnippet transformation at clone-for sniptest let-select snippet lockstep-transformation macroexpand-all* defslimefn with-emacs-package dothread-keeping-clj break failing-gracefully continuously dothread-keeping one-of? local-bindings returning keep-bindings dothread dothread-swank with-package-tracking with-timeout defhook with-connection label-value-line* with-swank-io call-being-tested expect only-mocked fake with-default-identity memfn-varargs with-connection when-feature with-default-session-options with-ssh-agent defcontract with-constraints contract defconstrainedfn toggle-button button-group radio-button radio-button-menu-item general-button add-action-listener button check-box check-box-menu-item combo-box add-listener label split-vertical shelf set-constraint! general-panel split-horizontal jlist stack text-field frame list-model tree panel scroll-panel add-list-selection-listener expect has-args times provide-contracts

Comments top

No comments for defmacro. Log in to add a comment.