Skip to content

Instantly share code, notes, and snippets.

@DarinM223
Created November 23, 2019 11:39
Show Gist options
  • Select an option

  • Save DarinM223/6b0040d8976421a3f4be5f9ccc132968 to your computer and use it in GitHub Desktop.

Select an option

Save DarinM223/6b0040d8976421a3f4be5f9ccc132968 to your computer and use it in GitHub Desktop.
Operator precedence parsing macro in Racket
(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