/var/log/messages

Nov 8, 2013 - 1 minute read - Comments - EoPL Scheme

EoPL の Exercise 2.14 (2)

なんか昨晩書いた試験が微妙、って思ったら pop は状態を変えるだけで値を取り出す手続きは別で存在してたんすね。いやはや。とりあえず微妙なのは以下の部分だった模様。

(test* "get top of stack"
       1
       (pop (push 1 (empty-stack))))

pop は値を戻すのではなくて stack を戻さないと。

(test* "get top of stack"
       empty-stack
       (pop (push 1 (empty-stack))))

ということで実装書く。つうか書いてみたら試験も色々駄目でした。

まず試験から。

(use gauche.test)
(add-load-path ".")
(load "stacks")

(test-start "stack")
(test-section "empty-stack")

(test* "empty-stack"
       '()
       (empty-stack))

(test-section "empty-stack?")
(test* "empty-stack"
       #t
       (empty-stack? (empty-stack)))

(test-section "push")
(test* "pushed stack is not empty"
       #f
       (empty-stack? (push 1 (empty-stack))))

(test-section "pop")
(test* "cannot pop from empty-stack"
       (test-error)
       (pop (empty-stack)))
(test* "get top of stack"
       (empty-stack)
       (pop (push 1 (empty-stack))))
(test* "after pop"
       #t
       (empty-stack? (pop (push 1 (empty-stack)))))

(test-section "top")
(test* "cannot get from empty-stack"
       (test-error)
       (top (empty-stack)))
(test* "top of _not empty-stack_ check"
       1
       (top (push 1 (empty-stack))))
(test* "top not pop"
       #f
       (empty-stack? (top (push 1 (empty-stack)))))

(test-end)

で、以下が実装です。

(define empty-stack
  (lambda ()
    '()))
(define empty-stack? null?)

(define push
  (lambda (value list)
    (cons value list)))
(define pop
  (lambda (list)
    (cdr list)))
(define top
  (lambda (list)
    (car list)))

empty-stack を手続きとして実装してなかったのが敗因? でも

(define empty-stack '())

な書き方であればそれに合わせて書けたのかも。

FSF に donate しようず、って言って 週末炊事

comments powered by Disqus