This program was taken from Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp by Peter Norvig, 1992, Morgan Kaufmann Publishers, Inc. If I compile and load it into a debug window, how would I use it?
; This function returns a random element of the list choices
(defun random-elt (choices)
"Choose an element from a list at random."
;; elt returns the (n + 1)th element of the list choices
;; random returns a random integer no large than the number of
;; elements in the list choices
(elt choices (random (length choices))))
; This function returns a random element of the given set and returns
; it in a list
(defun one-of (set)
"Pick one element of set, and make a list of it."
(list (random-elt set)))
; Define a sentence as a noun-phrase + verb phrase
(defun sentence () (append (noun-phrase) (verb-phrase)))
; Define a noun phrase as an article + noun
(defun noun-phrase () (append (Article) (Noun)))
; Define a verb phrase as a verb + a noun phrase
(defun verb-phrase () (append (Verb) (noun-phrase)))
; This function returns a randomly selected article
(defun Article () (one-of '(the a)))
; This function returns a randomly selected noun
(defun Noun () (one-of '(man ball woman table)))
; This function returns a randomly selected verb
(defun Verb () (one-of '(hit took saw liked)))
2
Answers
Looking at that code I see the only function not used in another is
sentence
. If you enter(sentence)
you’ll get a random sentence like:Typically I would edit the file using something like SLIME/Emacs, Clozure CL, LispWorks, Allegro CL … or anything other which has an editor which can talk to Common Lisp.
If you put the code in a buffer, then compile the buffer. In SLIME/Emacs use control-c control-k or meta-x slime-compile-and-load-file. This compiles the whole file and loads the compiled code into the running inferior Common Lisp.
In the LispWorks IDE I would just go into the buffer menu and execute compile.
Then go to the listener (aka REPL) and execute
(sentence)
. Page 34 to 38 in Norvig’s excellent book explain the code and how to use it in detail.