为什么这个表达式给我一个函数体错误? [英] Why is this expression giving me a function body error?

查看:41
本文介绍了为什么这个表达式给我一个函数体错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

I keep getting the error: define: expected only one expression for the function body, but found 1 extra part. I'm not understanding why I'm getting this.

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

NOTE TO SELF: When using DrRacket, Setting the language to BSL may make Racket commands error at compile time.

推荐答案

您使用的语言 (BSL) 只允许在程序体内部有一个表达式,如果有多个表达式,则需要将它们打包begin.

The language you're using (BSL) only allows a single expression inside the body of a procedure, if there's more than one expression, you need to pack them inside a begin.

还要注意 string-append 行没有做任何事情,您应该打印它或累积它.这是一个可能的解决方案,其中包含我的建议:

Also notice that the string-append line is doing nothing, you should print it or accumulate it. Here's a possible solution with my recommendations in place:

(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 为简单起见的过程:

Even better, use the printf procedure for simplicity's sake:

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

无论哪种方式,示例执行都如下所示:

Either way a sample execution looks like this:

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

这篇关于为什么这个表达式给我一个函数体错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆