标签:crete syntax 进入 ble fine str UNC cti parse
<FWAE> ::= <num>
| {+ <FWAE> <FWAE>}
| {- <FWAE> <FWAE>}
| {with {<id> <FWAE>} <FWAE>}
| <id>
| {fun {<id>} <FWAE>}
| {<FWAE> <FWAE>}
(define-type FWAE
[num (n number?)]
[add (lhs FWAE?) (rhs FWAE?)]
[sub (lhs FWAE?) (rhs FWAE?)]
[with (name symbol?) (named-expr FWAE?) (body FWAE?)]
[id (name symbol?)]
[fun (param symbol?) (body FWAE?)]
[app (ftn FWAE?) (arg FWAE?)])
(define (parse sexp)
(match sexp
[(? number?) (num sexp)]
[(list ‘+ l r) (add (parse l) (parse r))]
[(list ‘- l r) (sub (parse l) (parse r))]
[(list ‘with (list x i) b) (with x (parse i) (parse b))]
[(? symbol?) (id sexp)]
[(list ‘fun (list x) b) (fun x (parse b))]
[(list f a) (app (parse f) (parse a))]
[else (error ‘parse "bad syntax :~a" sexp)]))
(define (num+ x y)
(num (+ (num-n x) (num-n y))))
(define (num- x y)
(num (- (num-n x) (num-n y))))
(define (interp fwae)
(type-case FWAE fwae
[num (n) fwae]
[add (l r) (num+ (interp l) (interp r))]
[sub (l r) (num- (interp l) (interp r))]
[with (x i b) (interp (subst b x (interp i)))]
[id (s) (error ‘interp "free variable")]
[fun (x b) fwae]
[app (f a) (local [(define ftn (interp f))]
(interp (subst (fun-body ftn)
(fun-param ftn)
(interp a))))]))
(define (subst exp sub-id val)
(type-case FWAE exp
[num (n) exp]
[add (l r) (add (subst l sub-id val) (subst r sub-id val))]
[sub (l r) (sub (subst l sub-id val) (subst r sub-id val))]
[with (x i b) (with x
(subst i sub-id val)
(if (symbol=? sub-id x)
b
(subst b sub-id val)))]
[id (name) (cond [(equal? name sub-id) val]
[else exp])]
[app (f arg) (app (subst f sub-id val)
(subst arg sub-id val))]
[fun (id body) (if (equal? sub-id id)
exp
(fun id (subst body sub-id val)))]))
F1WAE : first-order functions
{deffun {f x} {+ 1 x}}
{f 10}
FWAE : first-class functions
{with {f {fun {x} {+ 1 x}}} {f 10}}
标签:crete syntax 进入 ble fine str UNC cti parse
原文地址:https://www.cnblogs.com/lastk/p/12838721.html