This works for me:

#lang racket

(define (hex:char x)
  (if (number? x)
      x
      (string->number (symbol->string x) 16)))

(define-syntax-rule (hex num ...) (bytes (hex:char (quote num)) ...))

(hex a b c 1 2 3) ; #"\n\v\f\1\2\3"

It’s almost always a mistake to use a function that manipulate syntax
object (syntax-e, etc.) inside syntax-rules, because syntax-rules don’t
give you an access to the syntax object. If you do want to manipulate
syntax object, use syntax-cases instead. In your case, however, the problem
is easy enough that you don’t need to directly manipulate syntax objects.

On Mon, Sep 9, 2019 at 12:12 PM Simon Haines <
simon.hai...@con-amalgamate.net> wrote:

> I'm trying to write a macro that will turn a list of hex literals into a
> byte string.
>
> (hex a b c 1 2 3) ; #"\n\v\f\1\2\3"
>
> After many hours I have finally come up with this:
>
> #lang racket
> (define-syntax hex
>   (syntax-rules ()
>     [(_ num ...)
>      (bytes
>       (let ([e (syntax-e #'num)])
>         (if (number? e) num
>             (string->number (symbol->string e) 16))) ...)]))
>
> (hex a b c 1 2 3)
>
> Of course there are many issues with checking the parameters etc. My
> problem is this generates "a: unbound identifier in: a" because the
> arguments are evaluated? If I remove the last line it works in the REPL OK.
>
> I suspect this is a small matter of my phases being mixed up, or a
> misunderstanding of when macros can be defined and used, or just outright
> ignorance on my part. I couldn't find any clues in the many, many
> references and tutorials I have read. I want to master them but I loathe
> creating macros, they always make me feel like an idiot, and I hope Racket2
> simplifies them somehow.
>
> Thanks for any help sorting this one out.
>
> --
> 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+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/racket-users/6d096642-b770-4655-acc5-08b36e176554%40googlegroups.com
> <https://groups.google.com/d/msgid/racket-users/6d096642-b770-4655-acc5-08b36e176554%40googlegroups.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 racket-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/racket-users/CADcuegveXyuSWqSts8Bk4D74aOaW-_BbJdV_q89Z5LNoG%2BGR9w%40mail.gmail.com.

Reply via email to