0

Could someone help me to convert this Scheme Code to Objective-C?

(define-type RCFAE
[num (n number?)]
[add (lhs RCFAE?) (rhs RCFAE?)]
[id (name symbol?)]
[fun (param symbol?) (body RCFAE?)]
[app (fun-expr RCFAE?) (arg-expr RCFAE?)]
[with (id symbol?) (named-expr RCFAE?) (body RCFAE?)]
[if0 (cond RCFAE?) (then RCFAE?) (else RCFAE?)]
[rec (id symbol?) (named-expr RCFAE?) (body RCFAE?)])


(define (subst e1 x e2)
(type-case RCFAE e1
[num (n) e1]
[add (l r) (add (subst l x e2) (subst r x e2))]
[id (y) (if (symbol=? x y) e2 (id y))]
[app (f a) (app (subst f x e2) (subst a x e2))]
[fun (param body)
(if (symbol=? param x)
e1
(fun param (subst body x e2)))]
[with (id named-expr body)
(if (symbol=? id x)
(with id (subst named-expr x e2) body)
(with id (subst named-expr x e2) (subst body x e2)))]
[rec (id named-expr body)
(if (symbol=? id x)
(rec id (subst named-expr x e2) body)
(rec id (subst named-expr x e2) (subst body x e2)))]
[if0 (cond then else)
(if0 (subst cond x e2) (subst then x e2) (subst else x e2))]))


; interp: RCFAE -> RCFAE
(define (interp expr)
(type-case RCFAE expr
[num (n) expr]
[add (l r) (num (+ (num-n (interp l)) (num-n (interp r))))]
[id (v) (error 'interp "free identifier")]
[fun (bound-id bound-body) expr]
[app (the-fun the-arg)
(local ([define fun-val (interp the-fun)]
[define arg-val (interp the-arg)])
(interp (subst (fun-body fun-val) (fun-param fun-val) arg-val)))]
[if0 (cond then else)
(if (zero? (num-n (interp cond)))
(interp then)
(interp else))]
[with (param named-expr body)
(interp (subst body param (interp named-expr)))]
[rec (param named-expr body)
(interp (subst body param (subst (interp named-expr) param (rec param named-expr (id param)))))]))

//some tests
(define test1
(with 'x (num 3)
(with 'f (fun 'y (add (id 'x) (id 'y)))
(with 'x (num 5)
(app (id 'f) (num 4))))))

(define test2 (rec 'sum (fun 'n
(if0 (id 'n)
(num 0)
(add (id 'n) (app (id 'sum) (add (id 'n) (num -1))))))
(app (id 'sum) (num 100))))

(test (interp test1) (num 7))

(test (interp test2) (num 5050))

1
Contributor
1
Reply
6
Views
5 Years
Discussion Span
Last Post by sarya_w
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.