Hatena::Groupcadr

わだばLisperになる このページをアンテナに追加 RSSフィード

2004 | 12 |
2005 | 01 | 02 | 07 | 10 | 11 |
2006 | 06 | 07 | 08 | 09 | 10 | 11 | 12 |
2007 | 01 | 02 | 03 | 04 | 05 | 06 | 07 | 08 | 09 | 10 | 11 | 12 |
2008 | 01 | 02 | 03 | 04 | 05 | 06 | 07 | 08 | 09 | 10 | 11 | 12 |
2009 | 01 | 02 | 03 | 04 | 05 | 06 | 07 | 08 | 09 | 10 | 11 | 12 |
2010 | 01 | 02 | 03 | 04 | 05 | 06 | 07 | 08 | 09 | 10 | 11 | 12 |
2011 | 01 | 02 | 03 | 04 | 05 | 06 | 07 | 11 |

2007-04-19

L-99 (訂正L-99.61)

| 14:30 | L-99 (訂正L-99.61) - わだばLisperになる を含むブックマーク はてなブックマーク - L-99 (訂正L-99.61) - わだばLisperになる

L-99 P61に挑戦を訂正 - L-99:Ninety-Nine Lisp Problems

P62の回答を作成しようと問題を読んでいて問題の意味

を取り違えていたことに気付いた。

葉っぱと節の定義を良く把握していなかったため、葉っ

ぱと節を区別しないで、実装していた(:.;゜;Д;゜;.:)

やり直しました。

P61

解答
;; Lisp Machine Lisp
(defun leafp (tree)
  (and tree
       (car tree)
       (atom (car tree))
       (null (cadr tree))
       (null (caddr tree))))

(defun count-leaves (tree)
  (if (null tree)
      0
    (if (leafp tree)
	1
      (+ (count-leaves (cadr tree))
	 (count-leaves (caddr tree))))))

;; Common Lisp
(defun leafp (tree)
  (and tree
       (car tree)
       (atom (car tree))
       (endp (cadr tree))
       (endp (caddr tree))))

(defun count-leaves (tree)
  (labels ((cpass (tree cont)
	     (if (endp tree)
		 (funcall cont 0)
		 (if (leafp tree)
		     (funcall cont 1)
		     (cpass (second tree)
			    #'(lambda (l)
				(cpass (third tree)
				       #'(lambda (r)
					   (funcall cont (+ l r))))))))))
    (cpass tree #'values)))

;; Scheme
(define (leaf? tree)
  (and (not (null? tree))
       (not (null? (car tree)))
       (not (pair? (car tree)))
       (null? (cadr tree)))
       (null? (caddr tree)))

(define (count-leaves tree)
  (let cpass ((tree tree)
	      (cont values))
    (if (null? tree)
	(cont 0)
	(if (leaf? tree)
	    (cont 1)
	    (cpass (cadr tree)
		   (lambda (l)
		     (cpass (caddr tree)
			    (lambda (r)
			      (cont (+ l r))))))))))
;