fork download
  1. #!/usr/bin/env racket
  2.  
  3. #lang racket
  4.  
  5. (require srfi/48)
  6.  
  7. (define *table* (hasheq '+ + '- - '* * '/ /))
  8.  
  9. (define (rpn exp)
  10. (let loop ((tokens (string-split exp)) (stack '()))
  11. (if (null? tokens)
  12. (car stack)
  13. (let ((token (car tokens)))
  14. (let ((num (string->number token)))
  15. (loop (cdr tokens)
  16. (cons
  17. (or num (apply (hash-ref *table* (string->symbol token))
  18. (reverse (take stack 2))))
  19. ((lambda (x)
  20. (if num
  21. x
  22. (drop x 2))) stack))))))))
  23.  
  24. (define (repl arg)
  25. (display "rpn > ")
  26. (with-handlers ((exn:fail?
  27. (lambda (v)
  28. (display "不正な入力です\n")
  29. (repl #f))))
  30. (repl
  31. (display
  32. (format "~1,4F~%" (let ((exp (read-line)))
  33. (if (string=? exp "quit")
  34. (exit)
  35. (rpn exp))))))))
  36.  
  37. (repl #f)
Success #stdin #stdout 0.57s 91052KB
stdin
6.1 5.2 4.3 * + 3.4 2.5 / 1.6 * -
stdout
Standard output is empty