为什么这个表达式给我一个函数体错误?

时间:2013-01-14 21:00:23

标签: scheme racket racket-student-languages

(define (subtract-1 n)
  (string-append "Number is: " (number->string n))
  (cond
    [(= n 0) "All done!"]
    [else (subtract-1(- n 1))]))

我不断收到错误: define:只需要一个函数体的表达式,但找到1个额外的部分。我不明白我为什么会这样做。< / p>

自我注意:使用DrRacket时,将语言设置为BSL可能会在编译时使Racket命令出错。

2 个答案:

答案 0 :(得分:4)

您正在使用的语言(BSL)仅允许在过程体内使用单个表达式,如果有多个表达式,则需要将它们打包在begin内。

另请注意,string-append行无效,您应该打印或累积它。这是我的建议的可能解决方案:

(define (subtract-1 n)
  (begin
    (display (string-append "Number is: " (number->string n) "\n"))
    (cond
      [(= n 0) "All done!"]
      [else (subtract-1 (- n 1))])))

更好的是,为简单起见,请使用printf程序:

(define (subtract-1 n)
  (begin
    (printf "~a ~s~n" "Number is:" n)
    (cond
      [(= n 0) "All done!"]
      [else (subtract-1 (- n 1))])))

无论哪种方式,样本执行都是这样的:

(subtract-1 3)
=> Number is: 3
=> Number is: 2
=> Number is: 1
=> Number is: 0
=> "All done!"

答案 1 :(得分:1)

球拍文档(Sequencing)似乎暗示您可能需要使用begin表达式才能工作,或者它可能是函数名称和参数之间(subtract-1(- n 1))中缺少的空格。

另外,您可能想要输出结果 string-append因为它并没有真正做任何事情。举例说明所有这些要点:

(define (subtract-1 n)
    (begin
        (write (string-append "Number is: " (number->string n)))
        (cond
            [(= n 0) "All done!"]
            [else (subtract-1 (- n 1))])))
相关问题