Code: Select all
(defun mappend (fn the-list)
"Apply fn to each element of list and append the results."
(apply #'append (mapcar fn the-list)))
(defun random-elt (choices)
"Choose an element from a list at random."
(elt choices (random (length choices))))
(defun rule-rhs (rule)
"the right hand side of a rule."
(rest rule))
(defun rewrites (category)
"return list of possible rewrites for that category."
(rule-rhs (assoc category *grammar*)))
(defparameter *simple-grammar*
'((sentence (noun-phrase verb-phrase))
(noun-phrase (Article Noun))
(verb-phrase (Verb noun-phrase))
(Article the a)
(Noun man ball woman table)
(Verb hit took saw liked))
"A grammar for a trivial subset of English.")
(defvar *grammar* *simple-grammar*
"The grammarused by generate. Initially,this is
*simple-grammar*, but we can switch to other grammars.")
Code: Select all
(defun generate (phrase)
"Generate a random sentence or phrase"
(if (listp phrase)
(mappend #'generate phrase)
(let ((choices (rewrites phrase)))
(if (null choices)
(list phrase)
(generate (random-elt choices))))))

BIOS