如何在Typed Racket中编写以多态函数作为参数的高阶函数? [英] How do I write higher-order functions that take polymorphic functions as arguments in Typed Racket?

查看:110
本文介绍了如何在Typed Racket中编写以多态函数作为参数的高阶函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

For example, how can I write a version of map that will work with polymorphic functions in Typed Racket? I use a simple id function defined as:

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

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

When I try to map it over a list i get an error:

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

推荐答案

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

You have to manually instantiate the polymorphism in this case:

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

原因在《类型化球拍指南》中进行了解释

The reason is explained in the Typed Racket Guide here:

Typed Racket的本地类型推断算法当前无法执行 推断用于高阶的多态函数的类型 本身是多态的参数.

Typed Racket’s local type inference algorithm is currently not able to infer types for polymorphic functions that are used on higher-order arguments that are themselves polymorphic.

(有关更多说明和示例,请参阅文档)

(see docs for more explanation and examples)

这篇关于如何在Typed Racket中编写以多态函数作为参数的高阶函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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