coerce
没有关于约束的默认标识是有原因的吗?
import Data.Coerce
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
newtype Id a = Id a
a :: Id Int
a = coerce 3 -- bad
-- • Couldn't match representation of type ‘a0’ with that of ‘Int’ arising from a use of ‘coerce’
-- • Ambiguous type variable ‘a0’ arising from the literal ‘3’
-- prevents the constraint ‘(Num a0)’ from being solved.
-- Probable fix: use a type annotation to specify what ‘a0’ should be.
-- These potential instances exist:
-- instance Num Integer -- Defined in ‘GHC.Num’
-- instance Num Double -- Defined in ‘GHC.Float’
-- instance Num Float -- Defined in ‘GHC.Float’
b :: Id Int
b = coerce (3 :: Int)
我想象它可以尝试用 a0 ~ Int
(或其他一般约束)来解决这个问题,因为身份(和合并约束)似乎总是一个选项
最佳答案
如果我正确理解了这个问题,我认为答案可能很无聊:没有人有想法和时间来完成将这种特殊情况添加到类型检查器所需的工程工作。我没有看到不这样做的技术原因,如果您每次都发出警告(或将其隐藏在语言扩展后面,或两者兼而有之),我认为 GHC HQ 很可能会接受这样的补丁。
关于haskell - Haskell 中具有约束的强制和身份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67397538/