3
votes

I am new to scheme. This is code sample from SICP course of MIT.

 (define (+ x y)
  (if (= x 0)
      y
      (+ (-1+ x) (1+ y))))

How do I convert this to Racket code? I want to convert to Racket because I am using DrRacket for running codes and I like that. It worked until now but complained about increment operators of scheme.

The errors I get are:

  1. define-values: cannot change constant variable: +
  2. reference to undefined identifier: -1+
2
What language are you using in DrRacket? Using a #lang based language (e.g., #lang racket), you can redefine primitives like + that are from the language. If you are using a student language, it will restrict you in order to provide better error reporting. - Asumu Takikawa
Just so you know, #lang scheme is an old backwards compatibility language. You probably want to just use #lang racket. I bet you're getting this error due to setting your memory limit too low or your program has a bug (e.g., infinite loop). - Asumu Takikawa
I wish this question to have an answer of how to run the above code in DrRacket IDE without manual translation. - Nakilon

2 Answers

12
votes

This will work fine in Racket:

(define (add x y)
  (if (= x 0)
      y
      (add (sub1 x) (add1 y))))

Some comments:

  • The name + for the procedure will be troublesome, because it will clash with the primitive add operation in Scheme; it's simpler if you use a different name, like add (this will fix the first error)
  • -1+ is not a procedure in Racket, replace it with sub1 (this will fix the second error). Optionally, you could define an alias for this procedure, like this: (define -1+ sub1)
  • 1+ is not a procedure in Racket, replace it with add1. Optionally, you could define an alias for this procedure, like this: (define 1+ add1)
  • Optionally: instead of (= x 0) you can write (zero? x)
2
votes

To fix the second error, change (-1+ x) to (- x 1) and (1+ y) to (+ y 1). This answer should help you with the first error.

If you want to use -1+ and 1+, you can define them yourself:

(define (1+ x) (+ x 1))
(define (-1+ x) (- x 1))