There are positions that macros can’t operate.
https://lexi-lambda.github.io/blog/2018/10/06/macroexpand-anywhere-with-local-apply-transformer/
explains this issue really well, so I recommend you to read it.

There’s also another issue, which is that you want write-proc to be named
write-proc, but Racket, which has a hygienic macro system, will “rename” it
automatically for you. So you need to explicitly indicate that you want the
name write-proc. Like this:

#lang racket

(require racket/struct)

(define-syntax (print-as stx)
  (syntax-case stx ()
    [(_ lam1 lam2)
     #`(define #,(datum->syntax stx 'write-proc)
         (make-constructor-style-printer
          lam1 lam2))]))

(struct point (x y)
  #:methods gen:custom-write
  [(print-as
   (lambda (obj) 'p)
   (lambda (obj)
     (list [point-x obj] [point-y obj])))])

(point 1 2)

On Wed, Sep 1, 2021 at 10:26 AM Dimaugh Silvestris
[email protected] <http://mailto:[email protected]>
wrote:

Tired of writing:
>
> #:methods gen:custom-write
>   [(define write-proc
>      (make-constructor-style-printer
>       (lambda (x) blablabla)
>       (lambda (x) blablabla)))]
>
> I made this macro:
>
> (define-syntax (print-as stx)
>   (syntax-case stx []
>     {[_ lam1 lam2]
>      #'[(define write-proc
>           (make-constructor-style-printer
>            lam1 lam2))]}))
>
> So I could just:
>
> (struct point (x y)
>   #:methods gen:custom-write
>   [print-as
>    (lambda (obj) 'p)
>    (lambda (obj)
>      (list [point-x obj] [point-y obj]))])
>
> But I get a bad syntax error. I've tried many subtle changes to no avail.
> What am I doing wrong?
>
> --
> You received this message because you are subscribed to the Google Groups
> "Racket Users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/racket-users/CAN4YmRH0jUXyG3YMKojrP2WSAKunrCjtN%3DyTFN2dPjmvvQDVdg%40mail.gmail.com
> <https://groups.google.com/d/msgid/racket-users/CAN4YmRH0jUXyG3YMKojrP2WSAKunrCjtN%3DyTFN2dPjmvvQDVdg%40mail.gmail.com?utm_medium=email&utm_source=footer>
> .
>

-- 
You received this message because you are subscribed to the Google Groups 
"Racket Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/racket-users/CADcuegshmaQGZbAUNOpmVZd0B0Wrt5Adu4BuJm1dpfnxqPFz4A%40mail.gmail.com.

Reply via email to