user893373
user893373

Reputation:

how do I convert this Scheme code to Racket

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+

Upvotes: 3

Views: 1526

Answers (2)

Óscar López
Óscar López

Reputation: 235984

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)

Upvotes: 12

benekastah
benekastah

Reputation: 5701

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

Upvotes: 2

Related Questions