1

Apologies if the question title is a bit confusing. Maybe after you are through reading it, you can suggest me a better title.

As a part of a homework assignment for an online course, I wrote an iterative procedure in mit-scheme to display number from 1 to a given number.

The code below works fine:

(define (count2-iter num)
    (define (iter counter)
        (cond ((> counter num) #t)
              (else (display counter)
                (iter (+ counter 1)))))
    (iter 1))

The output:

1 ]=> (load "count2-iter.scm")

;Loading "count2-iter.scm"... done
;Value: count2-iter

1 ]=> (count2-iter 10)
12345678910
;Value: #t

Personally I do not like using cond for 2 branches only and I tried to use if for this.

(define (count2-iter1 num)
    (define (loop idx)
        (if (> idx num)
            #t
            ((display idx)
             (loop (+ idx 1)))))
    (loop 1))

The output:

1 ]=> (count2-iter1 5)
5
;The object #!unspecific is not applicable.
;To continue, call RESTART with an option number:
; (RESTART 2) => Specify a procedure to use in its place.
; (RESTART 1) => Return to read-eval-print level 1.

Why is this? Shouldn't #t be evaluated the same way it was used in cond? Would really appreciate an explanation as I am still new to Scheme.

4

1 回答 1

5

试试这个:

(define (count2-iter1 num)
  (define (loop idx)
    (if (> idx num)
        #t
        (begin ; notice the difference!
          (display idx)
          (loop (+ idx 1)))))
  (loop 1))

原因如下:当您使用 时if,结果部分只能有一个表达式,而替代部分只能有一个表达式。如果需要多个表达式,我们必须用(begin ...). 您将表达式包围在 之间(...),这是不行的,因为括号用于函数应用程序(这就是错误消息指出 的原因The object #!unspecific is not applicable)。

另一方面,当满足条件时,a 对它的每个子句cond都有一个隐含的。就个人而言,我更喜欢在条件后需要多个表达式时begin坚持使用- 它不那么冗长。cond

于 2013-06-01T22:59:32.767 回答