Hatena::Groupcadr

bulbのLisp日記 RSSフィード

2008-01-06

[][]英文生成Lisp 19:41 英文生成Lisp - bulbのLisp日記 を含むブックマーク はてなブックマーク - 英文生成Lisp - bulbのLisp日記

Chapter1は、Common Lisp初心者用らしいですので、とりあえず飛ばしていきます。

英文生成

こんなルール

Sentence => Noun-Phrase + Verb-Phrase

Noun-Phrase => Article + Noun

Verb-Phrase => Verb + Noun-Phrase

Article => the, a, ...

Noun => man, ball, ...

Verb => hit, took, saw, ...


(defun sentence () 
  (append (noun-phrase) (verb-phrase)))
(defun noun-phrase ()
  (append (Article) (Noun)))
(defun verb-phrase ()
  (append (Verb) (noun-phrase)))
(defun Article ()
  (one-of '(the a)))
(defun Noun ()
  (one-of '(man ball woman table)))
(defun Verb ()
  (one-of '(hit took saw liked)))
(defun one-of (set)
  "Pick one element of set, and make a list of it."
  (list (random-elt set)))
(defun random-elt (choices)
  "Choose an element from a list at random."
  (elt choices (random (length choices))))

ちなみに環境は、CarbonEmacs + SLIME + SBCL です。

CL-USER> (sentence)
(THE BALL TOOK A BALL)
CL-USER> (sentence)
(THE BALL HIT THE MAN)
CL-USER> (sentence)
(THE MAN LIKED THE WOMAN)
CL-USER> (sentence)
(A BALL HIT THE MAN)
CL-USER> (noun-phrase)
(THE MAN)
CL-USER> (verb-phrase)
(SAW THE TABLE)

traceにかけてみる。

CL-USER> (trace sentence noun-phrase verb-phrase article noun verb)
(SENTENCE NOUN-PHRASE VERB-PHRASE ARTICLE NOUN VERB)
CL-USER> (sentence)
  0: (SENTENCE)
    1: (NOUN-PHRASE)
      2: (ARTICLE)
      2: ARTICLE returned (THE)
      2: (NOUN)
      2: NOUN returned (BALL)
    1: NOUN-PHRASE returned (THE BALL)
    1: (VERB-PHRASE)
      2: (VERB)
      2: VERB returned (SAW)
      2: (NOUN-PHRASE)
        3: (ARTICLE)
        3: ARTICLE returned (THE)
        3: (NOUN)
        3: NOUN returned (BALL)
      2: NOUN-PHRASE returned (THE BALL)
    1: VERB-PHRASE returned (SAW THE BALL)
  0: SENTENCE returned (THE BALL SAW THE BALL)
(THE BALL SAW THE BALL)

ルールを追加。

Noun-Phrase => Article+Adj*+Noun+PP*

Adj* => 0,Adj+Adj*

PP* => 0,PP+PP*

PP => Prep+Noun-Phrase

Adj => big,litle,red, ...

Prep => to,in,on,by, ...

(defun Adj* ()
  (if (= (random 2) 0)
      nil
      (append (Adj) (Adj*))))
(defun PP* ()
  (if (random-elt '(t nil))
      (append (PP) (PP*))
      nil))
(defun noun-phrase () (append (Article) (Adj*) (Noun) (PP*)))
(defun PP () (append (Prep) (noun-phrase)))
(defun Adj () (one-of '(big little blue green adiabatic)))
(defun Prep () (one-of '(to in by with on)))

CL-USER> (untrace sentence noun-phrase verb-phrase article noun verb)
T
CL-USER> (sentence)
(A LITTLE BLUE MAN HIT A TABLE IN A WOMAN BY A TABLE WITH A MAN ON THE BIG
 ADIABATIC MAN IN THE MAN)

adiabatic:断熱の