Created
November 23, 2019 11:39
-
-
Save DarinM223/6b0040d8976421a3f4be5f9ccc132968 to your computer and use it in GitHub Desktop.
Operator precedence parsing macro in Racket
This file contains hidden or 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
| (define-syntax (: stx) | |
| (syntax-parse stx | |
| ; #:literals needs to have bindings in order to work | |
| ; #:datum-literals only needs symbols so it works with '^'. | |
| #:datum-literals (+ - * / ^) | |
| [(_ l ... + r ...) #'(+ (: l ...) (: r ...))] | |
| [(_ l ... - r ...) #'(- (: l ...) (: r ...))] | |
| [(_ l ... * r ...) #'(* (: l ...) (: r ...))] | |
| [(_ l ... / r ...) #'(/ (: l ...) (: r ...))] | |
| [(_ l ... ^ r ...) #'(expt (: l ...) (: r ...))] | |
| [(_ ( x ... ) ) #'(: x ...)] | |
| [(_ x) #'x])) | |
| (: 1 + 2 * 3 - 2 ^ 2) ; => 3 | |
| (: 3 * (2 + 1 * 3) ^ 2) ; => 75 | |
| (: 3 * 5 ^ (1 + 1) + 3) ; => 78 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment