Unable to search from Racket macro

I have a function that does some processing of an expression:

(struct sym (s) #:transparent)

(define (foo-fn ex)
  (match ex
    [(? symbol? s) `(sym (quote ,s))]
    [(? list? xs) (cons (car xs) (map foo-fn (cdr xs)))]
    [x x]))

This function works as expected:

> (foo-fn '(cons x y))
'(cons (sym 'x) (sym 'y))

Now I'm trying to make a macro that takes an expression that it expresses and replaces it with the result foo-fn. I managed to find some of the ways:

(define-syntax-rule (foo ex)
  (foo-fn (quote ex)))

However, this macro still gives the quoted expression, and I would like that expression to be itself. That is, while my current code gives

> (foo (cons x y))
'(cons (sym 'x) (sym 'y))

I would prefer the result to be

> (foo (cons x y))
(cons (sym 'x) (sym 'y))

I managed to find a workaround with help eval, but I’m sure that this doesn’t mean that the macros are for use (correct me if I am wrong)

(define-syntax-rule (foo ex)
  (eval (foo-fn (quote ex))))

While the above works, I think this is the wrong way to use macros. What is the preferred approach?

+4
1

foo, foo-fn. foo-fn , , . , theres "" .

foo-fn , , , , foo . syntax/parse/define, :

(require syntax/parse/define)

(struct sym (s) #:transparent)

(define-syntax-parser foo
  [(_ s:id) #'(sym 's)]
  [(_ (f x ...)) #'(f (foo x) ...)]
  [(_ x) #'x])

, , . ( , "".)

foo :

> (foo (cons x y))
(cons (sym 'x) (sym 'y))
+4

Source: https://habr.com/ru/post/1656526/


All Articles