Skip to content

Instantly share code, notes, and snippets.

@dyokomizo
Last active August 29, 2015 14:07
Show Gist options
  • Save dyokomizo/df4ff71e33e378500e44 to your computer and use it in GitHub Desktop.
Save dyokomizo/df4ff71e33e378500e44 to your computer and use it in GitHub Desktop.
Interpreter for a polish notation "stack" language
#lang racket
(define eval [lambda (p ) (eval/s p '())])
(define eval/s [lambda (p s) (eval/k p s (lambda (x) x))])
(define eval/k
[lambda (p s k)
(cond {(eq? p '()) (k s)}
{(number? (car p)) (eval/k (cdr p) s [lambda (s) (k (cons (car p) s))])}
{(eq? (car p) 'dup) (eval/k (cdr p) s [lambda (s) (k (cons (car s) (cons (car s) (cdr s))))])}
{(eq? (car p) 'swap) (eval/k (cdr p) s [lambda (s) (k (cons (cadr s) (cons (car s) (cddr s))))])}
{else (cons 'err s)}
)
]
)
(eval '())
(eval '(1))
(eval '(1 2))
(eval '(dup 1))
(eval '(dup 1 2))
(eval '(dup dup 1))
(eval '(dup dup 1 2))
(eval '(swap 1 2))
(eval '(dup swap 1 2))
@dyokomizo
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment