Can I define a variable in the middle of a body?

Viewed 68

When a define is not in the outermost level of the program, can the define occur in the middle of a body? For example:

(define (f x)
  (display x)
  (define n 1)  ; <- Is this allowed?
  (+ n x))

Or must internal defines always occur at the beginning of a body? For example:

(define (f x)
  (define n 1)  ; <-
  (display x)
  (+ n x))
1 Answers

Definitions have to be at the beginning of a function body. From Section 5.3.2 of R7RS:

5.3.2. Internal definitions
Definitions can occur at the beginning of a <body> (that is, the body of a lambda, let, let*, letrec, letrec*, let-values, let*-values, let-syntax, letrec-syntax, parameterize, guard, or case-lambda). Note that such a body might not be apparent until after expansion of other syntax. Such definitions are known as internal definitions as opposed to the global definitions described above.

Related