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?
z
is not a free variable of(λz.y z)
and therefore not a free variable of(λx.(x (λz.y z))) x
. – PigmentationList.filter (fun y -> not (List.mem y (fv t'))) (fv t)
, while it seems correct to me so far, computesfv t'
way to many times. You should compute it once withlet fv_t' = fv t' in …
and usefv_t'
. – Pigmentationλ
in the lambda-calculus associates the same asfun
in OCaml. The expressionfun x -> st uff
is the same asfun x -> (st uff)
. – Pigmentationλ
was just likefun
in Caml”, so it is a valid question. Instead of deleting the question, you should write up your discovery as an answer and accept it. – Pigmentation