8

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

(: id : (All (A) A -> A))
(define (id x) x)

当我尝试将它映射到列表上时,出现错误:

> (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)))
4

1 回答 1

4

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

->  (map (inst identity Integer) '(1 2 3))
- : (Listof Integer) [more precisely: (Pairof Integer (Listof Integer))]
'(1 2 3)

原因在此处的 Typed Racket Guide 中进行了解释:

Typed Racket 的本地类型推断算法目前无法推断多态函数的类型,这些函数用于本身是多态的高阶参数。

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

于 2014-10-06T15:01:10.560 回答