如何在Typed Racket中编写将多态函数作为参数的高阶函数?

Dan*_*nov 8 types higher-order-functions racket polymorphic-functions typed-racket

例如,我如何编写一个版本的版本map将与Typed Racket中的多态函数一起使用?我使用一个简单的id函数定义为:

(: id : (All (A) A -> A))
(define (id x) x)
Run Code Online (Sandbox Code Playgroud)

当我尝试将其映射到列表时,我收到一个错误:

> (map id '(1 2 3))

Type Checker: Polymorphic function `map' could not be applied to arguments:
Types: (-> a b ... b c) (Listof a) (Listof b) ... b -> (Listof c)
   (-> a c) (Pairof a (Listof a)) -> (Pairof c (Listof c))
Arguments: (All (A) (-> A A)) (List One Positive-Byte Positive-Byte)
Expected result: AnyValues
   in: (map id (quote (1 2 3)))
Run Code Online (Sandbox Code Playgroud)

Asu*_*awa 5

在这种情况下,您必须手动实例化多态性:

\n\n
->  (map (inst identity Integer) \'(1 2 3))\n- : (Listof Integer) [more precisely: (Pairof Integer (Listof Integer))]\n\'(1 2 3)\n
Run Code Online (Sandbox Code Playgroud)\n\n

其原因在《打字球拍指南》中进行了解释

\n\n
\n

类型化 Racket\xe2\x80\x99s 本地类型推断算法当前无法\n 推断用于本身就是多态的高阶参数的多态函数的类型。

\n
\n\n

(有关更多解释和示例,请参阅文档)

\n