Last active
August 23, 2019 22:01
-
-
Save samdphillips/a62bcda26e7577ac2eba4dec6326f958 to your computer and use it in GitHub Desktop.
Sexp tree to postfix op
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/base | |
(require racket/match) | |
(define (op? e) | |
(match e | |
[(or '+ '- '* '/) #t] | |
[_ #f])) | |
(define (forthify e) | |
(match e | |
[(list (? op? o) a b) | |
(combine-forth (forthify a) o b)] | |
[(list (? op? o) a b c* ...) | |
(for/fold ([fexpr (forthify `(,o ,a ,b))]) ([c (in-list c*)]) | |
(combine-forth fexpr o c))] | |
[(? number? n) (list n)] | |
[(? symbol? x) (list x)])) | |
;; combine-forth :: forth-expr op lisp-expr -> forth-expr | |
(define (combine-forth fexpr op expr) | |
(append fexpr (forthify expr) (list op))) | |
(module+ test | |
(require chk) | |
(chk #:= (forthify '(+ 3 4)) '(3 4 +) | |
#:= (forthify '(* 3 4)) '(3 4 *) | |
#:= (forthify '(- 3 4)) '(3 4 -) | |
#:= (forthify '(/ 3 4)) '(3 4 /) | |
#:= (forthify '(+ 3 4 5)) '(3 4 + 5 +) | |
#:= (forthify '(+ 3 4 5 6)) '(3 4 + 5 + 6 +) | |
#:= (forthify '(+ (* 3 4) 4)) '(3 4 * 4 +) | |
#:= | |
(forthify '(+ a (* b (- c d) e) f)) | |
'(a b c d - * e * + f +) | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment