Skip to content

Instantly share code, notes, and snippets.

@digash
Created August 11, 2010 18:35
Show Gist options
  • Save digash/519483 to your computer and use it in GitHub Desktop.
Save digash/519483 to your computer and use it in GitHub Desktop.
(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