Returning defined syntax from a lambda expression

Suppose I want to return lexically scoped syntax from a defined function, e.g. like this:

(define (a x)
    (define (b y) (* y x))
    (define h (make-hash))
    (set! h 'b b)
    (define-syntax caller
      (syntax-rules ()
        ((_ i . args)
         (apply (hash-ref h 'i) args))))
    caller)

This doesn't work, it gives an error:

. caller: bad syntax in: caller

However:

> (define h (make-hash))
  (hash-set! h 'f (lambda (x) (* x x)))
> (define-syntax appl
    (syntax-rules ()
      ((_ f)
       (f ()))
      ((_ f (a ...))
       (f a ...))))
> (define-syntax caller
    (syntax-rules (h)
      ((_ i . args)
       (let ((f (hash-ref h 'i)))
         (appl f args)))))
> (caller f 5)
25

Seems to be a valid construct.

A macro is not a value, so you can not return a macro from a function. A macro does not exist at runtime.

More specifically, the caller: bad syntax in: caller error message you quoted is a syntax error: it happens because you tried to use just caller as an expression, but your macro only recognizes uses that match the template (caller i . args).

Is there a particular reason you were trying to “return” a macro instead of just returning a function?

(There are other problems with this code, too, but they seem secondary.)

I've developed a kind of OO framework, that can be used to define classes like this:

(roos (test a b) this (supers)
  (y a)
  (z b)
  ((g a) (* a (-> this y) (-> this z))
)

Later, I can create 'objects' of this definition, as follows:

> (define x (test 2 3))
> x
#<procedure:this>

I've created a call mechanism, using a -> syntax construct, and can call members of test:

> (-> x g 2)
12
> (-> x y)
2
> (-> x y! 50)
> (-> x g 2)
300

The same could be achieved by directly calling on x, as follows:

> (x 'y! 10)
> (x 'g 5)
150

However, I'd like to be able to omit the -> and also not use a symbol as a function-name, doing something like this:

> (x g 5)
150

However, this would require x to be a syntax transformer.

Or would there be some other way, e.g., I defined this syntax:

> (define-syntax mkvar
  (syntax-rules ()
    ((_ class-name var . other)
     var)))

(define-syntax mkcall
  (syntax-rules ()
    ((_ self m ())
     (self m))
    ((_ self m (a ...))
     (self m a ...))))

(define-syntax let-roos
  (syntax-rules ()
    ((_ ((name def) ...) body ...)
     (let ((self (mkvar name def))
           ...)
       (let-syntax
           ((name (syntax-rules ()
                    ((_ m . args)
                     (mkcall self 'm args))))
            ...)
         body
         ...)))))
> (let-roos ((b x))
          (b g 5))
150

However, that is not a nice construct, as:

> (let-roos ((b x))
            (let ((z b))
              (b g 5)))
. b: bad syntax in: b
> (let-roos ((b x))
            (let-roos ((z b))
                      (z g 5)))
. b: bad syntax in: b
> 

I hope this gives some insight to what I'm trying to achieve.