Skip to content

Instantly share code, notes, and snippets.

@vlastachu
Created April 12, 2014 21:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vlastachu/10558180 to your computer and use it in GitHub Desktop.
Save vlastachu/10558180 to your computer and use it in GitHub Desktop.
#lang racket
(define operators (hash '+ 5 '- 5 '* 10 '/ 10))
(define (priority operator)
(hash-ref operators operator 0))
(define (operator? operator)
(hash-has-key? operators operator))
(define (max-priority lst)
(argmax priority lst))
;упорядочить оператор
;target-op искомый оператор
;left - левый операнд; op - оператор; args - остальная часть выражения
(define (reverse-operator target-op left op . args)
(let ((right (car args)) (righter (cdr args)))
(if (eq? target-op op)
(append (list (list op left right)) righter)
(append (list left op) (apply reverse-operator target-op args))
)))
(define (reverse-operators expr)
(if (and (list? (car expr)) (eq? (cdr expr) '()))
(car expr)
(reverse-operators (apply reverse-operator (max-priority expr) expr))
))
(define (infix-to-prefix expression)
(let ((sub-parsed-list (map (λ (x) (if (list? x) (infix-to-prefix x) x)) expression)))
(reverse-operators sub-parsed-list)
))
(define-syntax (eval-infix stx)
(syntax-case stx ()
((eval-infix expr ...)
#'(infix-to-prefix (expr ...)))))
;simple example
(define (infix2prefix left operator right)
(operator left right)
)
(define a (eval-infix 2 + 2 * 2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment