我已经实现了一个基于这个编程任务的堆栈计算器。我想知道是否一个更有经验的骗子能给我反馈,并告诉我,如果我错过了什么在球拍,使解决方案更优雅。
#lang racket
(define (inc n)
(+ n 1))
(define (print-value s)
(begin
(display s)
(display " ")))
(define (exec l (stack empty) (opcount 1))
"executes a stack based program."
(cond
[(empty? l) (void)]
;; push number onto stack
[(number? (string->number (first l)))
(exec (rest l)
(cons (string->number (first l)) stack)
(inc opcount))]
;; pop number from stack
[(equal? (first l) ".")
(begin
(print-value (first stack))
(exec (rest l) (rest stack)
(inc opcount)))]
;; mathmatical operators
[(equal? (first l) "+")
(exec (rest l) (cons
(+ (first stack) (second stack))
(rest (rest stack))) (inc opcount))]
[(equal? (first l) "-")
(exec (rest l) (cons
(- (first stack) (second stack))
(rest (rest stack))) (inc opcount))]
[(equal? (first l) "*")
(exec (rest l) (cons
(* (first stack) (second stack))
(rest (rest stack))) (inc opcount))]
[(equal? (first l) "/")
(exec (rest l) (cons
(/ (first stack) (second stack))
(rest (rest stack))) (inc opcount))]
;; duplication operator
[(equal? (string-downcase (first l)) "dup")
(exec (rest l)
(cons (first stack) stack) (inc opcount))]
[else
(~a "Error: operation " opcount " invalid")]))
(define program (string-split "64 DUP * ."))
(exec program)发布于 2018-02-19 07:55:26
-和/运算符从典型的RPN顺序向后解释它们的操作数。也就是说,我希望"10 7 -"应该生成3,但实际上它会生成-3。
您的代码非常重复,因为每个操作符的处理程序必须获取操作符((first l)),执行操作,然后进行递归调用((exec (rest l) … (inc opcount)))。应该定义一个将操作符应用于堆栈的助手函数。
(define (apply-op op stack)
(cond
[(number? (string->number op))
(cons (string->number op) stack)]
[(equal? op ".")
(begin
(display (first stack))
(display " ")
(rest stack))]
[(equal? op "+")
(cons (+ (second stack) (first stack)) (rest (rest stack)))]
[(equal? op "-")
(cons (- (second stack) (first stack)) (rest (rest stack)))]
[(equal? op "*")
(cons (* (second stack) (first stack)) (rest (rest stack)))]
[(equal? op "/")
(cons (/ (second stack) (first stack)) (rest (rest stack)))]
[(equal? (string-downcase op) "dup")
(cons (first stack) stack)]
[else
(~a "operation '" op "' invalid")]))然后,exec函数只需调用它并驱动递归。
(define (exec ops (stack empty) (opcount 1))
"executes a stack based program."
(cond
[(empty? ops) (void)]
[else
(let ([next-stack (apply-op (first ops) stack)])
(if (string? next-stack)
(~a "Error at operator " opcount ": " next-stack)
(exec (rest ops) next-stack (+ opcount 1))))]))https://codereview.stackexchange.com/questions/187817
复制相似问题