将强制转换应用于类型化球拍中动态需要的功能

时间:2019-03-24 07:55:08

标签: racket typed-racket

我正在尝试在运行时从其他模块加载和使用函数。问题是dynamic-require的范围Any似乎无法cast设置为更特定的(函数)类型。

test.rkt:

#lang typed/racket

(module other-module typed/racket
  (provide f)
  (: f : Integer -> Integer)
  (define (f x)
    (* x 2)))

; g has type Any because dynamic-require returns a value of type Any
(define g (dynamic-require '(submod "test.rkt" other-module) 'f))

;contract violation
;  Attempted to use a higher-order value passed as `Any` in untyped code: #<procedure:f>
;  in: Any
;  contract from: typed-world
;  blaming: cast
;   (assuming the contract is correct)
((cast g (-> Integer Integer)) 3)

在运行时,有什么方法可以从#lang typed/racket中的其他模块加载和使用函数吗?

1 个答案:

答案 0 :(得分:2)

一种解决方法是在无类型的模块中进行加载,并使用require/typed来分配类型:

#lang typed/racket

(module other-module typed/racket
  (provide f)
  (: f : Integer -> Integer)
  (define (f x)
    (* x 2)))

(module another-module racket
  (define g (dynamic-require '(submod "test.rkt" other-module) 'f))
  (provide g))

(require/typed 'another-module
  (g (-> Integer Integer)))

(g 3)
;; 6

但是,如果dynamic-require可以采用目标类型,或者Typed Racket允许使用非类型化区域(与with-type相反),那就更好了。