Created
May 16, 2016 18:59
-
-
Save lallmon/c19343f01b23ad3e46c1a10d0f2b86e3 to your computer and use it in GitHub Desktop.
Clojure Data As Code Example
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
;; 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