首页 > 解决方案 > 在类型化球拍中使用应用构建结构

问题描述

我正在尝试在 Typed Racket 中使用 apply 构建结构列表,但无法弄清楚如何使其工作。我的猜测是它与多态函数的问题有关,但我无法找到解决方法。

这有效:

(struct tt ([a : Integer]
            [b : Integer]))

(apply tt '(1 2))

但这没有(已编辑):

(struct tt2 ([a : String]
             [b : (Vectorof Any)]))

(apply tt2 (list "A" (vector 1 2 2)))

出现错误:

 /usr/share/racket/collects/racket/private/kw.rkt:979:25: Type Checker: Bad
arguments to function in `apply':
Domain: String (Vectorof Any)
Arguments:  (List String (Vector Integer Integer Integer))

  in: (#%app apply tt23 (#%app list (quote "A") (#%app vector (quote 1) (quote 2) (quote 2))))

有什么解决办法吗?

标签: structpolymorphismtyped-racket

解决方案


向量是一种可变的数据结构,向量变异的可能性使得类型检查不那么直观。

A(Vectorof Integer)不能用作 a (Vectorof Any),因为 a(Vectorof Any)可能会在以后发生突变以包含非整数。像这样的程序不会进行类型检查

#lang typed/racket
(struct tt2 ([a : Integer]
             [b : (Vectorof Any)]))

(: v (Vectorof Integer)
(define v (vector 1 2 2))
(apply tt2 (list 1 v))

因为如果是这样,有人可以写(vector-set! (tt2-b ....) 0 "not a number"),然后v里面会有错误的类型。

解决方案是在创建向量时将每个向量注释为适当的类型。这意味着做以下事情之一:

  1. 替换(vector ....)(ann (vector ....) (Vectorof Any)).
  2. 如果向量直接创建为变量v,则替换(define v (vector ....))(define v : (Vectorof Any) (vector ....))

例如:

#lang typed/racket
(struct tt2 ([a : Integer]
             [b : (Vectorof Any)]))

(apply tt2 (list 1 (ann (vector 1 2 2) (Vectorof Any))))

请记住,这通常对于像向量这样的可变事物是必要的,但对于像列表这样的不可变事物则不然。


推荐阅读