简体   繁体   English

是否有 Typed Racket 提供的类型安全列表参考 function?

[英]Is there a type-safe list-ref function provided by Typed Racket?

Is there a type-safe list-ref function provided by Typed Racket?是否有 Typed Racket 提供的类型安全list-ref function?

The list-ref function appears to throw an error if you try to access an index that is out of bounds:如果您尝试访问超出范围的索引,则list-ref function 似乎会引发错误:

> (require typed/racket)
> (list-ref '(1 2 3) 100)
; list-ref: index too large for list
;   index: 100
;   in: '(1 2 3)

It makes sense that list-ref returns an error given its type: list-ref在给定类型的情况下返回错误是有道理的:

> list-ref
- : (All (a) (-> (Listof a) Integer a))

I would imagine that a type-safe version would have a type like the following:我想一个类型安全的版本将具有如下类型:

(: list-ref (All (a) (-> (Listof a) Integer (Option a)))

If this type-safe list-ref function is provided somewhere from Typed Racket, how would I have gone about finding it?如果这个类型安全的list-ref function 是从 Typed Racket 的某个地方提供的,我将如何找到它?

If this type-safe list-ref function doesn't exist, then why not?如果这个类型安全的list-ref function 不存在,那为什么不存在呢? It seems like this function would be generally useful.看起来这个 function 通常很有用。

It doesn't exist as far as I know.据我所知,它不存在。

One problem with your proposed (All (a) (-> (Listof a) Integer (Option a))) is that (Option a) is simply (U #fa) .您提出的(All (a) (-> (Listof a) Integer (Option a)))的一个问题是(Option a)只是(U #fa) That is, you must represent "none" with #f .也就是说,您必须用#f表示“无”。 But if you have a (Listof Boolean) , and list-ref* (your variant of list-ref ) returns #f , how can you tell if it's because to the index is out of bounds, or because the element is truly #f ?但是如果你有一个(Listof Boolean) ,并且list-ref* (你的list-ref的变体)返回#f ,你怎么知道是因为索引超出了界限,还是因为元素真的是#f ?

One possible way to fix this problem is by wrapping the "some" variant with something like a box, and adjust the type accordingly.解决此问题的一种可能方法是用类似盒子的东西包装“一些”变体,并相应地调整类型。 Eg,例如,

(: list-ref* (All (a) (-> (Listof a) Integer (Option (Boxof a)))))
(define (list-ref* xs i)
  (with-handlers ([exn:fail? (λ (_) #f)])
    (box (list-ref xs i))))

Mind you that wrapping will affect performance, and this might explain why it's not included in the library.请注意,包装会影响性能,这可以解释为什么它不包含在库中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM