gen:custom-write macro

23 views
Skip to first unread message

Dimaugh Silvestris

unread,
Sep 1, 2021, 1:26:16 PM9/1/21
to racket...@googlegroups.com
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?

Sorawee Porncharoenwase

unread,
Sep 1, 2021, 1:42:44 PM9/1/21
to Dimaugh Silvestris, Racket list

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)
--
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 racket-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/racket-users/CAN4YmRH0jUXyG3YMKojrP2WSAKunrCjtN%3DyTFN2dPjmvvQDVdg%40mail.gmail.com.

Reply all
Reply to author
Forward
0 new messages