I was just doing some homework for my upcoming OCaml test and I got into some trouble whatnot.
Consider the language of λ-terms defined by the following abstract syntax (where x is a variable):
t ::= x | t t | λx. t
Write a type term to represent λ-terms. Assume that variables are represented as strings.
Ok, boy.
# type t = Var of string | App of (t*t) | Abs of string*t;;
type t = Var of string | App of (t * t) | Abs of (string * t)
The free variables fv(t) of a term t are defined inductively a follows:
fv(x) = {x}
fv(t t') = fv(t) ∪ fv(t')
fv(λx. t) = fv(t) \ {x}
Sure thing.
# let rec fv term = match term with
Var x -> [x]
| App (t, t') -> (List.filter (fun y -> not (List.mem y (fv t'))) (fv t)) @ (fv t')
| Abs (s, t') -> List.filter (fun y -> y<>s) (fv t');;
val fv : t -> string list = <fun>
For instance,
fv((λx.(x (λz.y z))) x) = {x,y}.
Let's check that.
# fv (App(Abs ("x", App (Abs ("z", Var "y"), Var "z")), Var "x"));;
- : string list = ["y"; "z"; "x"]
I've checked a million times, and I'm sure that the result should include the "z" variable. Can you please reassure me on that?
In λ calculus all names are local to definitions. In the function λx.x we say that x is. “bound” since its occurrence in the body of the definition is preceded by λx. A name. not preceded by a λ is called a “free variable”.
In computer programming, the term free variable refers to variables used in a function that are neither local variables nor parameters of that function. The term non-local variable is often a synonym in this context.
A free variable is a variable that has no limitations, while a bound variable, on the other hand, is a variable with limitations. To determine whether your variable is free or bound, use these two criteria. Bound variables have limitations; free variables don't. Bound variables can be swapped; free variables can't.
Basically a free variable is a variable used in a lambda that is not one of the lambda's arguments (or a let variable). It comes from outside the context of the lambda. Eta reduction means we can change: (\x -> g x) to (g) But only if x is not free (i.e. it is not used or is an argument) in g .
In the comments to the OP it has been pointed out by the kind @PasqualCuoq that λ
in lambda calculus associates the same as fun
in OCaml. That is, the term t in λx.t
is evaluated greedily (see http://en.wikipedia.org/wiki/Lambda_calculus#Notation).
What this is means is that (λz.y z)
is actually (λz.(y z))
, and that the function above is correct, but the translation provided for the sample expression (λx.(x (λz.y z))) x
isn't, as it should've been
(App(Abs("x", App(Var "x", Abs("z", App(Var "y", Var "z")))), Var "x"))
in place of
(App(Abs ("x", App (Abs ("z", Var "y"), Var "z")), Var "x"))
Here's to this awesome place called Stack Overflow!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With