Hatena::Groupcadr

bulbのLisp日記 RSSフィード

2008-01-27

[][][]2.4 16:06 2.4 - bulbのLisp日記 を含むブックマーク はてなブックマーク - 2.4 - bulbのLisp日記

(defun cross-product (fn xlist ylist)
  (mappend #'(lambda (y)
	       (mapcar #'(lambda (x) (funcall fn x y))
		       xlist))
	   ylist))

(defun combine-all2 (xlist ylist)
  (cross-product #'append xlist ylist))

#|
CL-USER> (cross-product #'+ '(1 2 3) '(10 20 30))
(11 12 13 21 22 23 31 32 33)
CL-USER> (cross-product #'* '(1 2 3) '(10 20 30))
(10 20 30 20 40 60 30 60 90)
CL-USER> (cross-product #'- '(1 2 3) '(10 20 30))
(-9 -8 -7 -19 -18 -17 -29 -28 -27)
CL-USER> (cross-product #'list '(a b c d e f g h)
			'(1 2 3 4 5 6 7 8))

((A 1) (B 1) (C 1) (D 1) (E 1) (F 1) (G 1) (H 1) (A 2) (B 2) (C 2) (D 2) (E 2)
 (F 2) (G 2) (H 2) (A 3) (B 3) (C 3) (D 3) (E 3) (F 3) (G 3) (H 3) (A 4) (B 4)
 (C 4) (D 4) (E 4) (F 4) (G 4) (H 4) (A 5) (B 5) (C 5) (D 5) (E 5) (F 5) (G 5)
 (H 5) (A 6) (B 6) (C 6) (D 6) (E 6) (F 6) (G 6) (H 6) (A 7) (B 7) (C 7) (D 7)
 (E 7) (F 7) (G 7) (H 7) (A 8) (B 8) (C 8) (D 8) (E 8) (F 8) (G 8) (H 8))
|#

2008-01-08

[][][]2.1 21:29 2.1 - bulbのLisp日記 を含むブックマーク はてなブックマーク - 2.1 - bulbのLisp日記

generate を cond を使用して書きます。

;; Exercise 2.1

(defun generate (phrase)
  (let ((choices nil))
    (cond ((listp phrase)
	   (mappend #'generate phrase))
	  ((setf choices (rewrites phrase))
	   (generate (random-elt choices)))
	  (t
	   (list phrase)))))
#|
CL-USER> (generate 'sentence)
(THE WOMAN HIT A TABLE)
CL-USER> (generate 'sentence)
(THE TABLE LIKED A MAN)
|#



[][][]2.2 22:45 2.2 - bulbのLisp日記 を含むブックマーク はてなブックマーク - 2.2 - bulbのLisp日記

いきなり意味がわからなかったため答えを見る。

あぁ、明示的に終端と非終端を区別せよか。

答えは以下。

(defun generate (phrase)
  (cond ((listp phrase)
	 (mappend #'generate phrase))
	((non-terminal-p phrase)
	 (generate (random-elt (rewrites phrase))))
	(t
	 (list phrase))))

(defun non-terminal-p (category)
  (not (null (rewrites category))))

#|
CL-USER> (generate 'sentence)
(THE WOMAN TOOK A WOMAN)
CL-USER> (generate 'sentence)
(A WOMAN HIT THE TABLE)
|#