Created
October 7, 2013 14:36
-
-
Save edlich/6869051 to your computer and use it in GitHub Desktop.
Great Clojure Macro description!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(C) Mikera on Stackoverflow: | |
http://stackoverflow.com/questions/10434638/good-examples-of-clojure-macros-usage-which-demonstrate-advantages-of-the-langua/10435150 | |
I find macros pretty useful for defining new language features. In most languages you would need to wait for a new release of the language to get new syntax - in Lisp you can just extend the core language with macros and add the features yourself. | |
For example, Clojure doesn't have a imperative C-style for(i=0 ;i<10; i++) loop but you can easily add one with a macro: | |
(defmacro for-loop [[sym init check change :as params] & steps] | |
(cond | |
(not (vector? params)) | |
(throw (Error. "Binding form must be a vector for for-loop")) | |
(not= 4 (count params)) | |
(throw (Error. "Binding form must have exactly 4 arguments in for-loop")) | |
:default | |
`(loop [~sym ~init value# nil] | |
(if ~check | |
(let [new-value# (do ~@steps)] | |
(recur ~change new-value#)) | |
value#)))) | |
Usage as follows: | |
(for-loop [i 0, (< i 10), (inc i)] | |
(println i)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment