Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scheme/Racket - Macro to change order of procedure an arguments

I'd like to change the syntax of the following expression:

(> 2 1)

to something like:

(2 greater 1)

My first try is the following macro:

(define-syntax greater 
  (lambda (x)
    (syntax-case x (greater)
      [(a greater b)
       (syntax (> a b))])))

Using this macro fails with: "bad syntax in: greater"

I've been surfing some Scheme docs, but I was not able to find the way to do it.

like image 983
jdearana Avatar asked Dec 12 '22 21:12

jdearana


2 Answers

In Racket, there already exists a reader feature to allow for general infix notation: write a dot before and after the function or macro name: (2 . > . 1) It's a little verbose (the dots have to be surrounded by spaces), but I like it and use it a lot. See the documentation for more information.

like image 174
Paul Stansifer Avatar answered Mar 15 '23 16:03

Paul Stansifer


The expression (2 greater 1) is an application. It expands to (#%app 2 greater 1). You must define your own version of #%app and call it, say, my-%app. If greater is present swap the first and second argument, otherwise just expand to the standard #%app.

To use your new application you must export it from the file (module) in which you define it, and then import it in the module where your want your special application syntax.

like image 26
soegaard Avatar answered Mar 15 '23 17:03

soegaard