如何在类型化的球拍中定义语法? [英] How to do define-for-syntax in typed racket?

查看:59
本文介绍了如何在类型化的球拍中定义语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这有效

#lang racket

(begin-for-syntax
  (define (foo n)
    (+ n 3)))

所以我也希望它能起作用

So I would also expect this to work

#lang typed/racket

(: foo : Real -> Real)
(define-for-syntax (foo n)
  (+ n 3))

但是如果失败

; :: undefined;
;  cannot reference an identifier before its definition

此后,我依次尝试使用 typed/racket

After that I tried each of the following in turn in typed/racket

(define-for-syntax (foo (n : Real)) : Real
  (+ n 3))

(begin-for-syntax
  (: foo (-> Real Real))
  (define (foo n)
    (+ n 3)))

(begin-for-syntax
  (define (foo (n : Real)) : Real
    (+ n 3)))

每个失败都是由于一个或另一个原因.可能是 typed/racket 无法处理 {begin | define}-语法吗?

Each failed for one reason or another. Could it be that typed/racket can't handle {begin|define}-for-syntax?

推荐答案

#lang typed/racket

(: foo : Real -> Real)
(define-for-syntax (foo n)
  (+ n 3))

失败:

Type Checker: Declaration for `foo' provided, but `foo' has no definition

对我来说,这完全有道理. foo 是在阶段1中定义的,因此类型声明在阶段0中找不到其定义.

for me, which totally makes sense. foo is defined in phase 1, so the type declaration couldn't find its definition in phase 0.

(begin-for-syntax
  (: foo (-> Real Real))
  (define (foo n)
    (+ n 3)))

更正确",但是仍然有很多问题.该代码处于第1阶段,但是:是由第0阶段的 #lang类型/球拍导入的,因此会出现错误:

is more "correct", but still has a lot of problems. The code is in phase 1, but : is imported by #lang typed/racket in phase 0, so you get an error:

:: undefined

但是,另一个主要问题是,即使您在阶段1中成功导入了:,类型检查器仍将无法正常工作.

However, another major problem is that even if you manage to import : in phase 1, the type checker will still not work correctly.

简而言之,这就是使它起作用的方法.

To cut it short, here's how you could make it work.

#lang typed/racket

(module for-syntax-mod typed/racket
  (provide foo)
  (: foo (-> Real Real))
  (define (foo n)
    (+ n 3)))

(require (for-syntax 'for-syntax-mod))

(begin-for-syntax (println (foo 10)))

这会在 typed/racket 语言的子模块 for-syntax-mod 中声明 foo ,因此类型检查器现在可以在该子模块符合预期.然后,我们在阶段1导入此子模块,因此 foo 现在在 begin-for-syntax 中可用.请注意,语法开头中的代码仍未进行静态类型检查.

This declares foo in a submodule for-syntax-mod of the language typed/racket, so the type checker will now work on this submodule as expected. We then import this submodule at phase 1, so now foo is available inside begin-for-syntax. Note that code in begin-for-syntax is still not type checked statically.

这篇关于如何在类型化的球拍中定义语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆