;; ------------------------------------------------------------------------ ;; I riff on prefix->infix to create a compiler from Racket to Joy (almost) ;; ------------------------------------------------------------------------ #lang racket (require rackunit) (provide prefix->infix prefix->postfix) ;; -------------------------------------------------------------------------- ;; A solution to Problem 5 ;; -------------------------------------------------------------------------- (define prefix->infix (lambda (binary-exp) (list (numexp->infix (second binary-exp)) (first binary-exp) (numexp->infix (third binary-exp))))) (define numexp->infix (lambda (numexp) (if (number? numexp) numexp (prefix->infix numexp)))) ;; -------------------------------------------------------------------------- ;; A variation: convert prefix notation to *postfix* notation ;; -------------------------------------------------------------------------- (define prefix->postfix (lambda (binary-exp) (list (numexp->postfix (second binary-exp)) (numexp->postfix (third binary-exp)) ; just swap (first binary-exp)))) ; these two! (define numexp->postfix (lambda (numexp) (if (number? numexp) numexp (prefix->postfix numexp)))) ;; -------------------------------------------------------------------------- ;; Tests to make sure it works ;; -------------------------------------------------------------------------- ; from assignment (check-equal? (prefix->postfix '(+ 4 5)) '(4 5 +)) (check-equal? (prefix->postfix '(* (+ 4 5) (+ 7 6))) '((4 5 +) (7 6 +) *)) ; some new cases (check-equal? (prefix->postfix '(+ 1 (* 2 3))) '(1 (2 3 *) +)) (check-equal? (prefix->postfix '(/ (* 2 3) 4)) '((2 3 *) 4 /)) (define case1 '(* (* (+ 3 5) (- 3 (/ 4 3))) (- (* (+ 4 5) (+ 7 6)) 4))) (define case2 '(* (* (+ 3 5) (- 3 (/ 4 3))) (- 25 4))) (check-equal? (prefix->postfix case1) '(((3 5 +) (3 (4 3 /) -) *) (((4 5 +) (7 6 +) *) 4 -) *)) (check-equal? (prefix->postfix case2) '( ((3 5 +) (3 (4 3 /) -) *) (25 4 -) * )) ;; --------------------------------------------------------------------------