Skip to content

Instantly share code, notes, and snippets.

@darkf

darkf/rpn.rkt

Created Aug 12, 2012
Embed
What would you like to do?
Racket pure-functional RPN calculator
#lang racket
(define (op? e)
(member e '(+ *)))
(define (op->procedure op)
(case op
[(+) +]
[(*) *]))
(define (eval-rpn expr stack)
(cond
[(empty? expr) stack] ;; we're done, return the stack
[(number? (car expr)) ;; number
(eval-rpn (cdr expr) (cons (car expr) stack))] ;; push number on the stack
[(op? (car expr)) ;; operation
(let* ([op (car expr)]
[rhs (car stack)]
[lhs (cadr stack)]
[result ((op->procedure op) lhs rhs)]) ;; eval operation
(eval-rpn (cdr expr) (cons result (cddr stack))))] ;; push result; pop lhs/rhs
[else (error "unknown symbol")]))
(printf "result: ~a~%" (eval-rpn '(3 2 + 2 * 2 *) '()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.