Provide an example using "eval-syntax" & "syntax" in typed/racket

I have difficulty using typed/racket & the function "eval-syntax".
Can someone provide a compiling example

1 Like

This seems like the simplest thing, and it works:

#lang typed/racket

(eval-syntax #'(+ 1 2))

My guess is that you're trying something more complex but I don't know what.

the following does not compile

#lang typed/racket
(define  a
  (syntax '(+ 1 2)
          )
  )
(: b : Number )
(define  b
  (eval-syntax a))
(write  b)

Right, the problem is that eval-syntax doesn't know the type of the argument. If you annotate the result with AnyValues, and if you handle the possibility of multiple values, then it will work. But type checking code that's a value in your program is not something Typed Racket can do.

So as i understand there is no solution. Can i say typed/racket in this specific case accept any.
Or does this breaks the whole system.

1 Like

Or can i force it because i know beforehand what it will be

Maybe you can be more specific about what you want to do. A good way to think about this is to consider what you would do with arbitrary user input.

Something like this would work:

#lang typed/racket

(define stx (syntax (+ 1 2)))

(define-syntax-rule (cast-eval-syntax-single-val x t)
  (match (call-with-values (λ () (eval-syntax x))
                           (inst list Any))
    [(list y) (cast y t)]
    [_ (error 'not-expected-multiple-values)]))

(: result Number)
(define result
  (cast-eval-syntax-single-val stx Number))

(write result)

Note that your program has an extra ' inside (syntax ...), which would eval to a list, causing the cast to Number fail.

EDITED: This is even better.

#lang typed/racket

(define stx (syntax (+ 1 2)))

(define-syntax-rule (cast-eval-syntax-single-val stx t)
  (call-with-values
   (λ () (eval-syntax stx))
   (ann
    (case-lambda
      [(v) (cast v t)]
      [vs (error 'not-expected-multiple-values)])
    (-> Any * t))))

(: result Number)
(define result
  (cast-eval-syntax-single-val stx Number))

(write result)