user3542941
user3542941

Reputation: 9

Scheme R5RS: defining let expression

I was wondering how you would go about defining your own let expression in Scheme (I'm very new to scheme). I want it to look like (mylet id expr1 expr2) where id is bound to expr1's value and used in expr2. I think it would be something along the lines of:

(define (mylet x a body) 
  ((lambda (x) body) a) )

but that isn't working.

When I try

(mylet x 4 (* x 4))

I get the following error:

x: undefined; cannot reference undefined identifier. 

What am I doing wrong?

Upvotes: 1

Views: 598

Answers (1)

C. K. Young
C. K. Young

Reputation: 223023

let is actually a macro. You cannot define this as a procedure. Since you're using Racket, try this:

(define-syntax-rule (mylet x a body)
  ((lambda (x) body) a))

That looks almost like your original code, but using define-syntax-rule instead of define. ;-) That define-syntax-rule is actually a shortcut for the following full macro:

(define-syntax mylet
  (syntax-rules ()
    ((_ x a body)
     ((lambda (x) body) a))))

Indeed, you can even define the "standard" let macro (minus named let) this way:

(define-syntax-rule (let ((id val) ...) body ...)
  ((lambda (id ...) body ...) val ...))

Note the use of the ellipses (...). This allows zero or more forms; in this case, it allows let to contain multiple body forms.

Upvotes: 2

Related Questions