当在类型化 Racket 中预先不知道元数时,实例化可变多态过程的 "rest" 参数的类型
Instantiate the type of the "rest" parameter of a variadic polymorphic procedure when arity is not known in advance in typed Racket
假设我想转置一个 2 x n "matrix"(列表列表)mat
。在球拍中这样做的惯用方式是
(apply map list mat)
要在 typed/racket 中做同样的事情,我必须稍微帮助类型检查器。在这种情况下 map
的类型是
(All (c a b ...)
(-> (-> a b ... b c) (Listof a) (Listof b) ... b (Listof c)))
因为我处理的是 2 x n 矩阵,所以我必须将 a 和 b 都实例化为 Number
:
(apply (inst map (Listof Number) Number Number)
(inst list Number)
mat)
如果 mat
是一个 3 x n 矩阵,
(apply (inst map (Listof Number) Number Number Number)
(inst list Number)
mat)
会成功的。现在,假设我正在处理一个 m x n 矩阵,其中 m 是某个未知的正整数。是否有一种通用的方法来实例化适用于任何 m 值的地图?
谢谢 Sorawee Porncharoenwase,这几乎解决了我的问题。这是我所做的:
- 定义多态
zip
函数,如 link 中提供的:
(: zip (∀ (a) (-> (Listof a) (Listof a) * (Listof (Listof a)))))
(define (zip lst . lsts)
(apply map (inst list a) lst lsts))
- 应用于
mat
:
(apply zip (car mat) (cdr mat))
假设我想转置一个 2 x n "matrix"(列表列表)mat
。在球拍中这样做的惯用方式是
(apply map list mat)
要在 typed/racket 中做同样的事情,我必须稍微帮助类型检查器。在这种情况下 map
的类型是
(All (c a b ...)
(-> (-> a b ... b c) (Listof a) (Listof b) ... b (Listof c)))
因为我处理的是 2 x n 矩阵,所以我必须将 a 和 b 都实例化为 Number
:
(apply (inst map (Listof Number) Number Number)
(inst list Number)
mat)
如果 mat
是一个 3 x n 矩阵,
(apply (inst map (Listof Number) Number Number Number)
(inst list Number)
mat)
会成功的。现在,假设我正在处理一个 m x n 矩阵,其中 m 是某个未知的正整数。是否有一种通用的方法来实例化适用于任何 m 值的地图?
谢谢 Sorawee Porncharoenwase,这几乎解决了我的问题。这是我所做的:
- 定义多态
zip
函数,如 link 中提供的:
(: zip (∀ (a) (-> (Listof a) (Listof a) * (Listof (Listof a)))))
(define (zip lst . lsts)
(apply map (inst list a) lst lsts))
- 应用于
mat
:
(apply zip (car mat) (cdr mat))