Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Haskell 引用实例声明中的类型_Haskell - Fatal编程技术网

Haskell 引用实例声明中的类型

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

我试图使用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 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 #-}