Skip to content

Instantly share code, notes, and snippets.

@rik0
Created February 23, 2011 18:57
Show Gist options
  • Save rik0/840942 to your computer and use it in GitHub Desktop.
Save rik0/840942 to your computer and use it in GitHub Desktop.
PAIP grammar interpreter
(ns org.enrico_franchi.paip.simplegrammar.grammar
(:use clojure.core))
(def *simple-grammar*
'((sentence -> (noun-phrase verb-phrase))
(noun-phrase -> (Article Noun))
(verb-phrase -> (Verb noun-phrase))
(Article -> the a)
(Noun -> ball man woman table)
(Verb -> hit took saw liked)))
(def *grammar* *simple-grammar*)
(defn rule-lhs [rule]
"The left hand side of a rule."
(first rule))
(defn rule-rhs [rule]
"The right hand side of a rule."
(rest (rest rule)))
(defn get-rule [grammar category]
"Get the selected rule from the grammar"
(letfn [(key [rule]
(let [lhs (rule-lhs rule)]
(when (= lhs category) rule)))]
(some key grammar)))
(defn rewrites [category]
"Return a list of the possible rewrites for this category"
(rule-rhs (get-rule *grammar* category)))
(defn generate [phrase]
"Generate a random sentence or phrase."
(cond
(list? phrase) (mapcat generate phrase)
(seq (rewrites phrase)) (recur (rand-nth (rewrites phrase)))
:default (list phrase)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment