【问题标题】:Why is this expression giving me a function body error?为什么这个表达式给我一个函数体错误?
【发布时间】:2013-01-14 21:00:22
【问题描述】:
(define (subtract-1 n)
  (string-append "Number is: " (number->string n))
  (cond
    [(= n 0) "All done!"]
    [else (subtract-1(- n 1))]))

我不断收到错误消息:define: 只期望函数体有一个表达式,但发现了 1 个额外的部分。我不明白为什么会这样。

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

【问题讨论】:

  • (string-append...)(cond...) 都在函数体中。
  • @dotnetN00b:是的,BSL 是 Racket 的一种受限形式,其中函数的主体中只能有一个表达式。该限制旨在帮助将副作用与值混淆的初学者:它迫使您在没有副作用的情况下编写。如果你想要副作用,你需要在 BSL 之外。顺便说一句,在上面的代码中,似乎存在混淆:看起来你想打印一个小日志消息,但代码实际上是计算一个日志消息这不会被看到。

标签: scheme racket racket-student-languages


【解决方案1】:

您使用的语言 (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!"

【讨论】:

    【解决方案2】:

    Racket 文档 (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))])))
    

    【讨论】:

    • “你可能需要用额外的括号把正文包起来”
    • @OscarLopez 我的错。跟踪 Racket 文档并进行相应更新。
    猜你喜欢
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 2013-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多