Finish 2 minus1k
This commit is contained in:
43
Final/2.rkt
43
Final/2.rkt
@ -7,6 +7,7 @@
|
||||
[appE (fun-expr : Exp) (arg-expr : Exp)]
|
||||
[errorE (msg : String)] ;; New
|
||||
[if0E (test : Exp) (then : Exp) (else : Exp)]
|
||||
[minus1E (n : Exp)]
|
||||
)
|
||||
|
||||
(define-type Value
|
||||
@ -43,6 +44,7 @@
|
||||
(k : Continuation)]
|
||||
[doMinusK (v1 : Value)
|
||||
(k : Continuation)]
|
||||
[doMinus1K (k : Continuation)]
|
||||
[appArgK (arg-expr : Exp)
|
||||
(env : Env)
|
||||
(k : Continuation)]
|
||||
@ -77,8 +79,8 @@
|
||||
(lamE varE body))]
|
||||
[(s-exp-match? `(error STRING) sx) (errorE (s-exp->string (sx-ref sx 1)))]
|
||||
[(s-exp-match? `(error ANY) sx) (parse-error sx)]
|
||||
[(s-exp-match? `(ANY ANY) sx)
|
||||
(appE (px 0) (px 1))]
|
||||
[(s-exp-match? `(-- ANY) sx) (minus1E (px 1))]
|
||||
[(s-exp-match? `(ANY ANY) sx) (appE (px 0) (px 1))]
|
||||
[(s-exp-list? sx)
|
||||
(case (s-exp->symbol (sx-ref sx 0))
|
||||
[(+) (plusE (px 1) (px 2))]
|
||||
@ -113,7 +115,7 @@
|
||||
(interp fun-expr env (appArgK arg-expr env k))]
|
||||
[(if0E test-expr then-expr else-expr)
|
||||
(interp test-expr env (doIfK then-expr else-expr env k))]
|
||||
|
||||
[(minus1E n) (interp n env (doMinus1K k))]
|
||||
))
|
||||
|
||||
(define (continue [k : Continuation] [v : Value]) : Value
|
||||
@ -127,6 +129,8 @@
|
||||
(interp r env (doMinusK v next-k))]
|
||||
[(doMinusK v1 next-k)
|
||||
(continue next-k (arith-op - v1 v))]
|
||||
[(doMinus1K next-k)
|
||||
(continue next-k (arith-op - v (numV 1)))]
|
||||
[(appArgK arg-expr env next-k)
|
||||
(interp arg-expr env (doAppK v next-k))]
|
||||
[(doAppK fun-val next-k)
|
||||
@ -240,3 +244,36 @@
|
||||
{body-proc {lam {x} {{fX fX} x}}}}}}})
|
||||
(errorV "reached zero"))
|
||||
)
|
||||
|
||||
; unary decrement
|
||||
(module+ test
|
||||
(test (parse `{-- 2}) (minus1E (numE 2))))
|
||||
|
||||
(module+ test
|
||||
(test (run `{-- 2}) (numV 1))
|
||||
(test (run `{{lam {x} {-- x}} 3}) (numV 2))
|
||||
(test (run `{{lam {y} {+ {-- y} {-- y}}} 10}) (numV 18))
|
||||
(test (run `{{lam {f} {f 4}} {lam {x} {-- x}}}) (numV 3)))
|
||||
|
||||
; multiplication
|
||||
(module+ test
|
||||
(define fact-prog
|
||||
`{{lam {mkrec}
|
||||
{{lam {fact}
|
||||
;; Call fact on 5:
|
||||
{fact 5}}
|
||||
;; Create recursive fact
|
||||
{mkrec
|
||||
{lam {fact}
|
||||
{lam {n}
|
||||
{if0 n
|
||||
1
|
||||
{* n {fact {-- n}}}}}}}}}
|
||||
;; mkrec:
|
||||
{lam {body-proc}
|
||||
{{lam {fX}
|
||||
{fX fX}}
|
||||
{lam {fX}
|
||||
{body-proc {lam {x} {{fX fX} x}}}}}}})
|
||||
|
||||
(test (run fact-prog) (numV 120)))
|
Reference in New Issue
Block a user