1
(define (subtract-1 n)
  (string-append "Number is: " (number->string n))
  (cond
    [(= n 0) "All done!"]
    [else (subtract-1(- n 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.

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

Flux
  • 9,805
  • 5
  • 46
  • 92
dotnetN00b
  • 5,021
  • 13
  • 62
  • 95
  • Both `(string-append...)` and `(cond...)` are in the function body. – Roddy of the Frozen Peas Jan 14 '13 at 21:03
  • 2
    @dotnetN00b: yes, BSL is a restricted form of Racket where functions can only have one expression in their body. The restriction is meant to help beginners who confuse side-effects with values: it forces you to write without side-effects. If you want side effects, you need to be outside of BSL. By the way, in the code above, there appears to be confusion: it looks like you want to _print_ a little logging message, but the code is actually _computing_ a logging message that won't be seen. – dyoo Jan 14 '13 at 23:36

2 Answers2

5

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.

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))])))

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!"
Óscar López
  • 232,561
  • 37
  • 312
  • 386
1

Racket documentation (Sequencing) seems to suggest that you might need to use a begin expression for this to work, or it might be the missing space in (subtract-1(- n 1)) between the function name and the parameter.

Also, you probably want to output the result of string-append as it's not really doing anything as it is. Example to cover off all these points:

(define (subtract-1 n)
    (begin
        (write (string-append "Number is: " (number->string n)))
        (cond
            [(= n 0) "All done!"]
            [else (subtract-1 (- n 1))])))
Chamila Chulatunga
  • 4,856
  • 15
  • 17