Created
August 13, 2015 09:00
-
-
Save igalshilman/a1bcc412e7a318ff52fb to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| ;; code of a simple program that counts to zero. | |
| (def count-to-zero-code | |
| '(defn count-to-zero [n] | |
| (if (zero? n) | |
| 0 | |
| (count-to-zero (dec n))))) | |
| ;; simple AST | |
| (defrecord Function [name args body]) | |
| (defrecord If [condition then else]) | |
| (defrecord Literal [value]) | |
| (defrecord Sym [value]) | |
| (defrecord Apply [what args]) | |
| (defmulti parse | |
| (fn [sexpr] | |
| (cond | |
| (list? sexpr) (->> (first sexpr) | |
| keyword) | |
| (symbol? sexpr) :symbol | |
| :else :literal))) | |
| (defmethod parse :symbol [sexpr] | |
| (->Sym sexpr)) | |
| (defmethod parse :literal [sexpr] | |
| (->Literal sexpr)) | |
| (defmethod parse :defn [[_ name args body]] | |
| (->Function name args (parse body))) | |
| (defmethod parse :if [[_ condition then-clause else-clasue]] | |
| (->If (parse condition) | |
| (parse then-clause) | |
| (parse else-clasue))) | |
| (defmethod parse :default [[what & args]] | |
| (->Apply (parse what) | |
| (map parse args))) | |
| (println | |
| (parse count-to-zero-code)) | |
| ;#Function{:name count-to-zero, :args [n], | |
| ; :body #If{:condition #Apply{:what #Sym{:value zero?}, :args (#Sym{:value n})}, | |
| ; :then #Literal{:value 0}, | |
| ; :else #Apply{:what #Sym{:value count-to-zero}, :args (#Apply{:what #Sym{:value dec}, :args (#Sym{:value n})})}}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment