Skip to content

Instantly share code, notes, and snippets.

@lallmon
Created May 16, 2016 18:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lallmon/c19343f01b23ad3e46c1a10d0f2b86e3 to your computer and use it in GitHub Desktop.
Save lallmon/c19343f01b23ad3e46c1a10d0f2b86e3 to your computer and use it in GitHub Desktop.
Clojure Data As Code Example
;; The code starts as a string in a text file, like any programming language.
"(defn f [x]
(* x x))"
;; Then it's read by the reader.
(with-in-str
"(defn f [x]
(* x x))" (read))
;; Read returns this data structure:
'(defn f [x]
(* x x))
;; Which is a list of 4 elements,
;; Two symbols: defn and f
;; A vector which contains a symbol: [x]
;; And a list with three symbols: (* x x)
;; The function eval then transforms this data structure to jvm bytecode
(eval '(defn f [x]
(* x x))) ;;=> #'user/f
;; A nice consequence of this is that it allows macros
;; Which can be thought of as functions that take a code data structure
;; and returns another data structure that is then eval'd
(defmacro rev [form] (reverse form))
(rev (2 3 *)) ;;=> (* 3 2) ;;=> 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment