print symbol and evaluate it with a macro

Viewed 73

I am trying to write some code to print a symbol and evaluate the function associated with it in racket

I already managed to achieve this at runtime using eval, but I think this ought to be possible also without using eval.

Eval version:

(define ns (namespace-anchor->namespace a))

(define (deco-display fun-sym bstr)
  (display (symbol->string fun-sym))
  (display ": ")
  (display (eval `(,fun-sym ,bstr) ns)))

example usage:

(define (extract-id bstr)  (subbytes bstr  0  8 ))
(deco-display 'extract-id   bstr)

I tried:

(define (xxx) (display "asdas"))

(define-syntax (print-and-do stx)
  (syntax-case stx ()
    [(_ p) #`(begin (display #'p) (newline) (p))]))

but the outcome is not what I expected

(print-and-do xxx)
.#<syntax:interactions from an unsaved editor:5:16 xxx>
asdas
1 Answers

Thanks to people commenting and some more reading I wrapped up 3 working versions:

(define-syntax (print-and-do-v1 stx)
  (syntax-case stx ()
    [(_ p) #'(begin (display (syntax->datum #'p)) (newline) (p))]))

(define-syntax (print-and-do-v2 stx)
  (syntax-case stx ()
    [(_ p) #'(begin (display 'p) (newline) (p))]))

(define-syntax-rule (print-and-do-v3 p)
  (begin (display 'p) (newline) (p)))
Related