初学者方案:如何使二进制算术表达式成为字符串。

时间:2013-03-25 19:37:25

标签: scheme racket

我想将二进制算术表达式更改为字符串,并且我在使用它的递归部分时遇到问题。到目前为止,我只能做基本的两个。

(define-struct bae (fn arg1 arg2))
;; A binary arithmetic expression (binexp) is either
;; a number, or 
;; a structure (make-bae f a1 a2), where
;;   f is a symbol in the set'*,'+,'-,and'/,
;;   a1 is a binexp, and 
;;   a2 is a binexp.

(define (binexp->string b)
  (cond 
    [(number? b) (number->string b)]
    [else (string-append "(" (number->string (bae-arg1 b)) (symbol->string(bae-fn b))
              (number->string (bae-arg2 b))
              ")")]))

(check-expect (binexp->string 5) "5")
(check-expect (binexp->string (make-bae '* 3 4)) "(3*4)")
(check-expect (binexp->string ((make-bae '+
(make-bae '* (make-bae '+ 4 1)
(make-bae '+ 5 2))
(make-bae '- 6 3))) "(((4+1)*(5+2))+(6-3))")

这最后一次检查是我不知道该怎么办。任何帮助都会有所帮助,谢谢!

1 个答案:

答案 0 :(得分:1)

你很亲密。您必须使用binexp->stringarg1上的arg2进行递归:

(define (binexp->string b)
  (if (number? b)
      (number->string b)
      (string-append "("
                     (binexp->string (bae-arg1 b))
                     (symbol->string (bae-fn   b))
                     (binexp->string (bae-arg2 b))
                     ")")))