Created
October 9, 2014 15:36
-
-
Save amnn/028050811054662e059d to your computer and use it in GitHub Desktop.
Earley Parser in Clojure (Some helper functions are missing).
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
(defn recogniser | |
"Returns the recogniser function for the grammar `g`." | |
[g] | |
(let [nullable? (nullable g) | |
g (null-free g) | |
init (initial-state (nullable? :S))] | |
(letfn [(consume-token [{:keys [index items] :as state} tok] | |
(loop [processed? #{} | |
items items | |
state (reset-state state)] | |
(if (seq items) | |
(let [item (peek items)] | |
(if (processed? item) | |
(recur processed? (pop items) state) | |
(case (classify item) | |
:shift | |
(recur (conj processed? item) | |
(pop items) | |
(if (= tok (next-sym item)) | |
(update-in state [:items] | |
conj (shift item)) | |
state)) | |
:reduce | |
(let [r-key (redux-key item)] | |
(recur (conj processed? item) | |
(->> (get-in state [:redux r-key]) | |
(map shift) | |
(into (pop items))) | |
(update-in state [:complete] conj r-key))) | |
:predict | |
(let [nt (next-sym item) | |
r-key [index nt] | |
predicted? (contains? (:redux state) r-key) | |
state (if predicted? | |
state | |
(assoc-in state [:redux r-key] #{})) | |
items (pop (if (nullable? nt) | |
(conj items (shift item)) | |
items))] | |
(recur | |
(conj processed? item) | |
(if predicted? | |
items | |
(into items | |
(->> (rule-seq g nt) | |
(map #(->Item % index 0))))) | |
(update-in state [:redux r-key] conj item)))))) | |
state)))] | |
(fn [toks] | |
(-> (->> (conj (vec toks) nil) | |
(reduce consume-token init) | |
:complete) | |
(contains? success-key)))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment