Reputation: 21
I would like to write an interpreter for if and cond statements in scheme, however I couldnt do cond part.My cond has else part always.
<cond -> ( cond <conditional_list> <else_condition> )
<conditional_list -> <conditional | <conditional <conditional_list
<conditional -> ( <expr <expr )
<else_condition -> ( else <expr )
Here is my if part :
((if-stmt? e)
(if (not (eq? (my_interpreter (cadr e) env) 0))
( my_interpreter (caddr e) env)
( my_interpreter (cadddr e) env)))
Any help is appreciated thank you!
Upvotes: 0
Views: 146
Reputation:
As a comment says: don't handle cond
: turn it into if
. for instance (this may not get all of the semantics of cond
correct in Scheme and is casual about errors):
(define (rewrite-cond cond-expr)
(if (and (list? cond-expr)
(eqv? (first cond-expr) 'cond))
(rewrite-cond-clauses (rest cond-expr))
(error 'rewrite-cond "not a cond")))
(define (rewrite-cond-clauses clauses)
(if (null? clauses)
'#f
(let ((this (first clauses))
(more (rest clauses)))
(let ((test (first this))
(body (rest this)))
`(if ,(if (eqv? test 'else) '#t test)
(begin ,@body)
,(rewrite-cond-clauses more))))))
Now
> (rewrite-cond '(cond ((x) 1 3)
(y 2)
(else 3)))
(if (x) (begin 1 3) (if y (begin 2) (if #t (begin 3) #f)))
Upvotes: 1