You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Typed Racket是否存在unsafe cast函数?需绕过类型系统断言

Solution for Unsafe Cast in Typed Racket (Like Haskell's unsafeCoerce)

Let's break down your problem first: the standard cast fails because it tries to create a runtime contract for your function type with a postcondition, and Typed Racket can't generate contracts for those kinds of function types. To get the "trust me, I know what I'm doing" behavior similar to Haskell's unsafeCoerce, you need to bypass both the contract generation and type checker's verification.

Method 1: Use cast with the #:unsafe Argument

The built-in cast has an optional #:unsafe flag that tells Typed Racket to skip all runtime contract checks and fully trust your type assertion. This is the simplest approach:

#lang typed/racket

(: func (-> (Listof String) Boolean))
(define (func x) (eq? (length x) 2))

; Use #:unsafe to skip contract generation
(: func2 (-> (Listof String) Boolean : (List String String)))
(define func2 (cast func (-> (Listof String) Boolean : (List String String)) #:unsafe))

Method 2: Use unsafe-cast from typed/racket/unsafe

If you prefer a more explicit "unsafe" operation, you can import unsafe-cast from the typed/racket/unsafe module. This function completely bypasses both type checking and contract generation, just like Haskell's unsafeCoerce:

#lang typed/racket
(require typed/racket/unsafe)

(: func (-> (Listof String) Boolean))
(define (func x) (eq? (length x) 2))

; Explicit unsafe cast
(: func2 (-> (Listof String) Boolean : (List String String)))
(define func2 (unsafe-cast func (-> (Listof String) Boolean : (List String String))))

Critical Warning

Just like unsafeCoerce in Haskell, these operations are unsafe. If your predicate func ever returns #t for a list that doesn't have exactly two elements, using func2 will lead to silent runtime type errors (since the type system assumes the postcondition holds, but the actual data doesn't match). Only use these when you're 100% confident your logic correctly enforces the proposition you're asserting.

内容的提问来源于stack exchange,提问作者illabout

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:55:30