Scheme:不能在if语句中使用#t

时间:2013-06-01 22:36:51

标签: scheme iteration mit-scheme

如果问题标题有点令人困惑,请道歉。也许在你阅读之后,你可以建议我一个更好的头衔。

作为在线课程作业的一部分,我在mit-scheme中编写了一个迭代程序,以显示从1到给定数字的数字。

以下代码可以正常使用:

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

输出:

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

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

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

我个人不喜欢只使用cond 2个分支,我尝试使用if

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

输出:

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.

这是为什么?不应该以与cond中使用的方式相同的方式评估#t吗?非常感谢解释,因为我还是Scheme的新手。

1 个答案:

答案 0 :(得分:4)

请改为尝试:

(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)的原因。

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