我想将二进制算术表达式更改为字符串,并且我在使用它的递归部分时遇到问题。到目前为止,我只能做基本的两个。
(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))")
这最后一次检查是我不知道该怎么办。任何帮助都会有所帮助,谢谢!
答案 0 :(得分:1)
你很亲密。您必须使用binexp->string
和arg1
上的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))
")")))