Problem 8: Infix (optional, 0pts)
One annoying thing about Scheme is that it can only understand arithmetic operations that are written in prefix notation. That is, if I want to evaluate an expression, the arithmetic operator must come first, which is different than in math class.
Let’s leverage our skills to define a Scheme macro infix
that accepts arithmetic operations with infix notation, which places operators between operands as you are used to. You only need to support the addition and multiplication operators *
and +
.
There are 2 ways to solve this problem -- calculate the value of the expression directly, or just adjust the order of operators and operands.
There are 4 test cases in our Online Judge, their requirements are detailed in the table below.
Test Case | Extra Restrictions on expr |
---|---|
8.1 | Atomic operands are all numbers, expr is either an atomic operand or a three-element list (expr op expr) . |
8.2 | expr is either an atomic operand or a three-element list (expr op expr) . |
8.3 | Atomic operands are all numbers. |
8.4 | None. |
If you choose to solve only 8.1 and 8.2, the solution can be very simple (less than 120 characters), give a try!
(define-macro (infix expr)
''YOUR-CODE-HERE
)
;;; Tests
; scm> (define x 5)
; x
; scm> (infix ((1 + 2) * (3 + 4)))
; 21
; scm> (infix ((1 + 2) * (3 + x)))
; 24
; scm> (infix (1 + 2 * 3 + 4))
; 11
; scm> (infix (1 + 2 * 3 + x))
; 12