So, I experiment and create a programming language created in the circuit. I also built an interpreter for it, which is part of the code below.
I would like to rewrite the interpreter so that it creates closures with smaller environments, i.e. when constructing a closure, it uses an environment that is similar to the current environment, but contains only variables that are free variables in the functional part of the closure. I am learning memoization, but it is confusing.
EDIT: I now use the equivalent of a racket, so if it's easier, you should give me suggestions.
(define-struct var (string)) ;; a variable, eg, (make-var "foo") (define-struct int (num)) ;; a constant number, eg, (make-int 17) (define-struct add (e1 e2)) ;; add two expressions (define-struct fun (name formal body)) ;; a recursive 1-argument function (define-struct closure (fun env)) ;; closures (made at run-time) (define (envlookup env str) (cond [(null? env) (error "unbound variable during evaluation" str)] [(equal? (caar env) str) (cdar env)] [#t (envlookup (cdr env) str)])) (define (eval-prog p) (letrec ([f (lambda (env p) (cond [(var? p) (envlookup env (var-string p))] [(int? p) p] [(add? p) (let ([v1 (f env (add-e1 p))] [v2 (f env (add-e2 p))]) (if (and (int? v1) (int? v2)) (make-int (+ (int-num v1) (int-num v2))) (error "TTPL addition applied to non-number")))] [(fun? p) (make-closure p env)] [(closure? p) p] [#t (error "bad TTPL expression")]))]) (f () p)))
source share