Created
August 12, 2012 22:37
-
-
Save darkf/3335005 to your computer and use it in GitHub Desktop.
Racket pure-functional RPN calculator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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