Skip to content

Instantly share code, notes, and snippets.

@pancanin
Created September 23, 2019 22:56
Show Gist options
  • Save pancanin/7b4dad857a61e1f2a69b133593d24132 to your computer and use it in GitHub Desktop.
Save pancanin/7b4dad857a61e1f2a69b133593d24132 to your computer and use it in GitHub Desktop.
Expression eval in Racket
; Small interpreter
; (Const (Add 1 (Add-v 2 3))) = 6
(define (Const? x) (eq? x `Const))
(define (Add? x) (eq? x `Add))
(define (eval_expr exp)
(cond [(Const? (car exp))
(if (number? (cdr exp))
(cdr exp)
(eval_expr (cdr exp)))]
[(Add? (car exp))
(if (number? (car (cdr exp)))
(if (number? (cdr (cdr exp)))
(+ (car (cdr exp)) (cdr (cdr exp)))
(+ (car (cdr exp)) (eval_expr (cdr (cdr exp)))))
(if (number? (cdr (cdr exp)))
(+ (eval_expr (car (cdr exp))) (cdr (cdr exp)))
(+ (eval_expr (car (cdr exp))) (eval_expr (cdr (cdr exp))))))]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment