In scheme you can define functions which return a lambda expression and use them to define new functions. For example, you can write this code
(define (pow-iter base exp r)
(if (= exp 1)
r
(pow-iter base (- exp 1) (* base r))))
(define (pow exp)
(lambda (base)
(pow-iter base exp base)))
(define cubic (pow 3))
(cubic 2)
We have here a function pow
which takes the exponent as argument and evaluates to a lambda function which evaluates to the nth power of the given base.
However, if we put that within a scope like this:
(define (do-cubic x)
(define (pow-iter base exp r)
(if (= exp 1)
r
(pow-iter base (- exp 1) (* base r))))
(define (pow exp)
(lambda (base)
(pow-iter base exp base)))
(define cubic (pow 3))
(cubic x))
(do-cubic 2)
I get an error
pow: undefined; cannot use before initialization
Why does this error occur and is there any way to fix it without changing the logic of the program?
#!racket
. In#!r5rs
, even under RacketVM, it should fail. They are different languages. – Sylwester