(define (rpn expression) (define (operator? exp) (let ((token (car exp))) (or (eqv? '+ token) (eqv? '- token) (eqv? '* token) (eqv? '/ token)))) (define (operator exp) (car exp)) (if (null? expression) "there is nothing to calculate!" (let calculate ((exp expression) (stack '())) (cond ((null? exp) (car stack)) ((operator? exp) (let* ((first-operand (cadr stack)) (second-operand (car stack)) (result (eval (list (operator exp) first-operand second-operand) ;; eval needs a second arg ;; this works for guile, at least: (interaction-environment)))) (calculate (cdr exp) (cons result (cddr stack))))) (else (calculate (cdr exp) (cons (car exp) stack))))))) (define (reached-newline?) (let ((c (peek-char))) (cond ((eq? c #\newline) (read-char) #t) ((char-whitespace? c) (read-char) (reached-newline?)) (else #f)))) (define (main expression) (cond ((reached-newline?) (write (rpn expression)) (newline) (main '())) (else (main (append expression (list (read))))))) (main '())