I am trying to have a better understanding about free and bound variables. Here is an example code:
(define (what-kind-of-var? guess x)
(< (abs (- (square guess) x))
0.001))
I see that bound variables here would be guess
and x
, and free variables <
, abs
, -
, and square
. What if I called what-kind-of-var?
recursively? Would it be a bound variable because it is binding itself?
Thanks!
guess
and x
are parameters. They're eventually bound (to respective arguments) when the function is applied.
<
, abs
, -
, are actually bound to procedures in the initial environment. So they're not free variables.
square
would be the free variable, subject to the fact that what-kind-of-var?
is not defined in its scope. (note that sqr
is bound in the initial environment).
what-kind-of-var?
is also not unbound, even if it calls itself recursively (assuming recursion is implemented properly in the language). (define (f param) body)
can be seen as (define f (lambda (param) body)
It would, under dynamic binding, but Scheme has lexical scoping.
But actually it is neither. "Free" or "bound" comes from lambda calculus. what-kind-of-var?
is a top-level variable , naming that lambda expression,
(define what-kind-of-var?
(lambda (guess x) ;; this
(< (abs (- (square guess) x))
0.001)))
but in lambda calculus expressions cannot be named. The only way to call it recursively in lambda calculus is to use Y combinator:
((Y (lambda (what-kind-of-var?) ;; outer
(lambda (guess x) ;; inner
(if (< (abs (- (square guess) x))
0.001)
guess
(what-kind-of-var? (+ 1 guess) x)))))
4 25)
and now of course what-kind-of-var?
is bound inside that new lambda expression under Y
. It's free in the nested, inner lambda, but bound in the outer one.
You need to read a handbook of logic or lambda calculus, there is the origin of the concepts of variable.
When a variable is inside a function and that function takes as parameter that variable, it is bound, whatever the function is recursive or not.
The idea of binding means that a location of memory is allocated and the variable symbol denotes that location. Not every bound location can be accessed by a variable.
In the case of free variables, there are many ways to bind it to something (in C language some free variables are bound by the linking process and some are never bound). In Lisp, there are many ways a free variable can be bound -- dynamic binding, static/scope binding, or in lisp_N , with N > 2
there are lots of different ways to bind a variable. But whatever the implementation of a variable is, the origin of the concept comes from math logic.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.