Skip to content

Instantly share code, notes, and snippets.

@bayan
Created August 12, 2012 11:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bayan/3331552 to your computer and use it in GitHub Desktop.
Save bayan/3331552 to your computer and use it in GitHub Desktop.
Ruby's array of words and symbols shortcuts in Clojure - an example of how macros can be used to implement language level features that are present in other languages
;; Ruby has a short cut to specify an array of words: %w(apple bee carrot) → ["apple", "bee", "carrot"]
;; This can't be implemented in Ruby itself, and requires the language designers to implement this (in C).
;; Clojure, being a Lisp, allows anyone to add such a feature directly using a macro:
(defmacro %w [& args] `(map str '~args))
(%w apple bee carrot)
;; → ("apple" "bee" "carrot")
;; What about a list of Clojure keywords (known as symbols in Ruby)?
;; This is coming in Ruby 2.0. But again, Clojure programmers wouldn't need to wait for the language designers:
(defmacro %i [& args] `(map keyword '~args))
(%i apple bee carrot)
;; → (:apple :bee :carrot)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment