Another solution:

 

#lang racket

 

(define-syntax (def-both-phases stx)

(syntax-case stx ()

  ((_ rest ...)

#'(begin

    (define rest ...)

     (define-for-syntax rest ...)))))

 

(def-both-phases (my-function x) (+ x 1))

 

(define-syntax my-macro

  (lambda (stx)

    (datum->syntax stx (my-function (cadr (syntax->datum stx))))))

 

(my-macro 5)

(my-function 7)

 

Jos

 

From: Yushuo Xiao
Sent: domingo, 9 de mayo de 2021 10:00
To: Racket Users
Subject: [racket-users] How to define a function that can be used both in syntax transformers and ordinary code?

 

I am using syntax transformers to define macros in Racket. I want to create some helper functions to help me manipulate the syntax. However, the functions I defined outside the syntax transformer are not available inside the syntax transformer. For example, in the following code

 

(define (my-function x) (+ x 1))

 

(define-syntax my-macro

  (lambda (stx)

    (datum->syntax stx (my-function (cadr (syntax->datum stx))))))

 

I got the error "my-function: reference to an unbound identifier at phase: 1; the transformer environment".

 

After some searching, I am able to write the following code so that `my-function` is available inside the syntax transformer.

 

(begin-for-syntax

  (define (my-function x) (+ x 1)))

(provide (for-syntax my-function))

 

(define-syntax my-macro

  (lambda (stx)

    (datum->syntax stx (my-function (cadr (syntax->datum stx))))))

 

But the problem is, `my-function` is not available outside the syntax transformer this time. Sometimes I want to check those helper functions in ordinary code, so I need to be able to call it from both inside and outside the syntax transformer, just like the function `cadr`. How can I achieve that?

 

I know my question has something to do with Racket's syntax model, in particular the concept of "phase level", but I never really understand it. If you could provide some easy-to-follow tutorials explaining it I would even be more grateful.

 

(Also, I have asked the same question on StackOverflow before I am aware of this Google group. Is this place more suitable for asking Racket questions like this than StackOverflow? Should I delete the question on StackOverflow?)

--
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/244a3fc8-e24f-4121-a09f-3bd6d2c6b140n%40googlegroups.com.

 

--
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/ADFCA8F8-72A0-4F1F-89B1-CE28BBEF4017%40hxcore.ol.

Reply via email to