Created
August 11, 2010 18:35
-
-
Save digash/519483 to your computer and use it in GitHub Desktop.
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
(ns hw1 (:refer-clojure :exclude [eval])) | |
(defrecord StringLit [s]) | |
(defrecord Concat [l r]) | |
(defrecord RestAfter [l r]) | |
(defn parse [sexp] | |
(cond (symbol? sexp) (StringLit. (str sexp)) | |
(sequential? sexp) | |
(case (second sexp) | |
'& (Concat. (parse (first sexp)) (parse (nth sexp 2))) | |
'% (RestAfter. (parse (first sexp)) (parse (nth sexp 2))) | |
:else (throw (IllegalArgumentException. (str "bad list: " sexp)))) | |
:else (throw (IllegalArgumentException. (str "bad arg: " sexp))))) | |
(defprotocol Interpreter | |
(eval [this])) | |
(extend-protocol Interpreter | |
StringLit | |
(eval [s] (:s s)) | |
Concat | |
(eval [c] (str (eval (:l c)) (eval (:r c)))) | |
RestAfter | |
(eval [ra] | |
(let [l (eval (:l ra)) | |
r (eval (:r ra)) | |
i (.indexOf l r)] | |
(if (< i 0) | |
(throw (Exception. (str r " not found in " l))) | |
(.substring l (+ i 1)))))) | |
(-> '[a & [b & c] % b] parse eval) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment