[plt-scheme] Infix to prefic

From: Jens Axel Søgaard (jensaxel at soegaard.net)
Date: Sun May 23 17:08:42 EDT 2004

Anton's nice infix macros on comp.lang.scheme made
me brush up some old code original used to have
a convenient input syntax for polynomials.

(module infix mzscheme
   (require (lib "match.ss" "mzlib"))
   (provide infix->prefix)

   (define (infix->prefix exp)
     ; Convert an infix expression to prefix
     (define ip infix->prefix)
     (define (nott sym)  (lambda (x) (not (eq? x sym))))
     (define (non-op? s) (not (member s '(+ - * / ^))))
     (match exp
       [(? number? r)                          r]                     ; number
       [(? symbol? s)                          s]                     ; variable
       [((? non-op? s) (x ...))                `(,s ,@(map ip x))]    ; function call
       [(p)                                    (ip p)]                ; parentheses
       [('- exp)                               `(- ,(ip exp))]        ; sign
       [('+ exp)                               `(+ ,(ip exp))]        ; sign
       [((and p (? (nott '+))) ... '+ q ...)   `(+ ,(ip p) ,(ip q))]
       [((and p (? (nott '-))) ... '- q ...)   `(- ,(ip p) ,(ip q))]
       [((and p (? (nott '*))) ... '* q ...)   `(* ,(ip p) ,(ip q))]
       [((and p (? (nott '/))) ... '/ q ...)   `(/ ,(ip p) ,(ip q))]
       [((and p (? (nott '^))) ... '^ q ...)   `(^ ,(ip p) ,(ip q))]
       [_  (error "infix->prefix: The following is not a legal infix
                   representation of an arithmetical expression: " exp)]))
)

 >(require (lib "defmacros.ss"))
 >(define-macro (: . infix)
    (infix->prefix infix))
 >(define x 3)
 > (: sin(x) + 1 * tan(2))
-2.0439198552016515

The observant reader will by now have noticed that / and ^ associate
the wrong way, but that's not my problem. My problem is the expansion
time of the above match expression. If the two lines with / and ^ is
commented out the above is evalueted almost immediately.

Is there a more a suitable way to write the match expression?

-- 
Jens Axel Søgaard



Posted on the users mailing list.