I'm trying to implement letrec using mathematical lambda notation for the function, but I'm having difficulty. My assignment says that let can be defined as
p(e1) U (p(e2) - {x})
and that letrec can be defined as
(p(e1) - {f x}) U (p(e2) - {f})
I've successfully implemented let to find freevars in an expression, but I'm struggling with letrec implementation:
let rec fv (e:expr) : S.t = match e with
| Id name -> S.singleton name
| Value x -> S.empty
| Lambda(name, body) -> S.remove name (fv body)
| Let(name, def, body) -> S.union (fv def) (S.diff (fv body) (S.singleton name))
| App (e1, e2) | Add (e1, e2) | Sub (e1, e2) | Mul (e1, e2) | Div (e1, e2) | Lt (e1, e2) | Eq (e1, e2) | And (e1, e2) -> S.union (fv e1) (fv e2)
Can someone please walk me through how to do this? Do I have to use Lambda? I'm pretty lost at this point and implementations just trying to follow the definition must have been done incorrectly on my part because I can't quite get it working.
After reading your question many times, I realized you're trying to calculate the free variables of an expression like this:
The essence of
let recis that appearances ofxine1are taken to refer to the value ofxthat is being defined. Soxis not free ine1. And like the non-recursivelet,xis not free ine2either. It's bound to the valuee1.So I would have thought the implementation would look like this:
The definition you give doesn't make sense (to me), especially since there's no obvious meaning for
f.One could imagine restricting this form to cases where x is a function. Maybe that's what the assignment is telling you.
If you give a few more details, maybe someone a little more versed in these things can help.