Skip to content

Instantly share code, notes, and snippets.

@Denommus
Last active December 16, 2015 09:48
Show Gist options
  • Select an option

  • Save Denommus/5415395 to your computer and use it in GitHub Desktop.

Select an option

Save Denommus/5415395 to your computer and use it in GitHub Desktop.
A calculator using reverse polish notation, written in Common Lisp
#!/usr/bin/sbcl --script
(loop for n = (read t)
for stack = (list n) then (cons n stack)
until (member n '(exit quit))
do (unless (numberp n)
(cond
((endp (nthcdr 2 stack))
(format t "Not enough numbers in stack~%")
(pop stack))
(t
(let ((fun (pop stack))
(op2 (pop stack))
(op1 (pop stack)))
(push (funcall fun op1 op2) stack)))))
(format t "(~{~A~^ ~})~%" (reverse stack)))
@Denommus

Copy link
Copy Markdown
Author

Using "do" instead of "loop":

#!/usr/bin/sbcl --script

(do ((stack '())
     (n (read t) (read t)))
    ((member n '(exit quit)) nil)
  (push n stack)
  (unless (numberp n)
    (cond ((endp (nthcdr 2 stack))
           (format t "Not enough numbers in stack~%")
           (pop stack))
          (t
           (let ((fun (pop stack))
                 (op2 (pop stack))
                 (op1 (pop stack)))
             (push (funcall fun op1 op2) stack)))))
  (format t "(~{~A~^ ~})~%" (reverse stack)))

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