Skip to content

Instantly share code, notes, and snippets.

@yamasushi
Last active November 13, 2023 06:40
Show Gist options
  • Save yamasushi/625b1f5b289dedd6cbb5709cb33f6c60 to your computer and use it in GitHub Desktop.
Save yamasushi/625b1f5b289dedd6cbb5709cb33f6c60 to your computer and use it in GitHub Desktop.
infix --> postfix
gosh$ (i2p '(2 ^ < 6 - 7 > + 3 * 4))
(6 7 - ^ 3 4 * +)
;
; infix --> postfix
; https://gist.github.com/yamasushi/625b1f5b289dedd6cbb5709cb33f6c60
; expr -> expr + term1 { print + } | expr - term1 { print - } | term1
; term1 -> term1 * term2 { print * }| term1 / term2 { print / }| term2
; term2 -> <number> { print <number>.val }| ( expr )
; expr -> term1 rest1
; rest1 -> + term1 { print + } rest1_1
; | - term1 { print - } rest1_1
; | ε
; term1 -> term2 rest2
; rest2 -> * term2 { print * } rest2_1
; | / term2 { print / } rest2_1
; | ε
; factor -> <number> { print <number>.val }
; | ( expr )
(define (i2p x) ($ car $ expr (cons '() x) ) )
(define (restx syms termx par)
(define (_restx_ par)
;(format #t "_restx_ par=~s~%" par)
(let ( {inh (car par)}
{xs (cdr par) } )
(if (null? xs)
`(,inh)
(let ( {hd (car xs)}
{tl (cdr xs)} )
(if (find (cut eq? hd <>) syms)
($ _restx_
$ (^y
;(format #t "| ~s | ~s | ~s |~%" inh (car y) `(,hd) )
(cons
(append (car y) `(,hd) )
(cdr y)
))
$ termx (cons inh tl) )
par
)
)
)
)
)
;(format #t "restx syms=~s par=~s~%" syms par)
(_restx_ par)
)
(define (expr par) ($ rest1 $ term1 par) )
(define rest1 (cut restx '(+ -) term1 <>) )
(define (term1 par) ($ rest2 $ term2 par) )
(define rest2 (cut restx '(* / %) term2 <>))
(define (term2 par) ($ rest3 $ term3 par) )
(define rest3 (cut restx '(^) term3 <>) )
(define (term3 par) (factor par))
(define (factor par)
;(format #t "factor par=~s~%" par)
(let ( {inh (car par)}
{xs (cdr par) } )
(if (null? xs)
(error "factor:error xs=~s" xs)
(let ( {hd (car xs)}
{tl (cdr xs)} )
(cond
{(of-type? hd <number>)
(cons
(append inh `(,hd) )
tl)}
{(eq? hd '< )
($ (cut match-term '> <>) $ expr (cons '() tl) )}
{else
(error "factor:error xs=" xs) }
)
)
)
)
)
(define (match-term t par)
;(format #t "match-term t=~s , par=~s~%" t par)
(let ( {inh (car par)}
{xs (cdr par) } )
(if (null? xs)
(error "syntax error xs=" xs)
(if (equal? (car xs) t)
(cons inh (cdr xs))
(error "syntax error xs=" xs)
)
)
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment