Haskell 引用实例声明中的类型
我试图使用undefined来获取类型常量的值(类似于storable中的Haskell 引用实例声明中的类型,haskell,Haskell,我试图使用undefined来获取类型常量的值(类似于storable中的sizeOf) 但是,这会产生一个错误: Could not deduce (MyClass a0) arising from a use of ‘typeConst’ from the context (Read a, MyClass a) bound by the instance declaration at src/Main.hs:13:10-49 The type variable ‘a0’ is ambig
sizeOf
)
但是,这会产生一个错误:
Could not deduce (MyClass a0) arising from a use of ‘typeConst’
from the context (Read a, MyClass a)
bound by the instance declaration at src/Main.hs:13:10-49
The type variable ‘a0’ is ambiguous
Note: there is a potential instance available:
instance MyClass Int -- Defined at src/Main.hs:20:10
In the second argument of ‘($)’, namely
‘typeConst (undefined :: a)’
In the expression: length $ typeConst (undefined :: a)
In an equation for ‘len’: len = length $ typeConst (undefined :: a)
考虑到我将
typeConst
参数的类型显式指定为a
类型变量,它由MyClass a
绑定,我不明白类型推断有什么问题,因此,在我看来,应用typeConst
函数应该没有问题。您需要启用scopedTypeVariables
扩展名,以便通过ghc
标志-XScopedTypeVariables
或通过文件顶部的pragma来工作:
{-# LANGUAGE ScopedTypeVariables #-}
如果在类实例中使用,则无需执行任何特殊操作,因为来自类头的类型变量已经在范围中,但是,如果您想在简单的顶级函数中使用它,您需要在类型签名中为所有使用一个显式的
。您需要使用ScopedTypeVariables
扩展名:否则,where
子句中的a
不会被识别为与之前绑定的类型相同,而是一个新类型变量(因此出现了a0
与a
的问题)。@gallais谢谢,这是可行的。现在等着有人写下来作为答案。但是我读了一些关于这个扩展的文章,现在我不明白为什么它在没有显式的情况下对所有的都有效?(我在非类函数中尝试了类似的方法,但没有成功。直到我为all添加了一个instance
)我猜想实例声明是一种特殊情况:如果为all a声明instance。(…)=>MyClass(可能是a)
例如,您会得到一个格式错误的实例。
{-# LANGUAGE ScopedTypeVariables #-}