Created
April 12, 2014 21:37
-
-
Save vlastachu/10558180 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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