Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/10.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 Typeclass实例将Int转换为Num a?_Haskell_Type Inference - Fatal编程技术网

Haskell Typeclass实例将Int转换为Num a?

Haskell Typeclass实例将Int转换为Num a?,haskell,type-inference,Haskell,Type Inference,我试图创建一个返回Repa形状的变量函数: class Indexable r where idx :: [Int] -> r instance Indexable Int where idx [x] = x instance (Indexable b) => Indexable (Int :. b) where idx (x:xx) = x :. (idx xx) instance (Indexable a) => Indexable (Z :. a) wh

我试图创建一个返回Repa形状的变量函数:

class Indexable r where
  idx :: [Int] -> r

instance Indexable Int where
  idx [x] = x

instance (Indexable b) => Indexable (Int :. b) where
  idx (x:xx) = x :. (idx xx)

instance (Indexable a) => Indexable (Z :. a) where
  idx xs = Z :. (idx xs)

instance (Indexable r) => Indexable (Int -> r) where
  idx xs = \x -> idx (x:xs)
它的工作原理是:

> fromListUnboxed (idx [] (3 :: Int)) [1..3] :: Array U DIM1 Int
AUnboxed (Z :. 3) [1,2,3]
但是我必须显式地使用3::Int,而不仅仅是3,尽管我的实例显式地使用Int。下面的内容让我感到困惑:

> :t idx [] 3
idx [] 3 :: (Num a, Indexable (a -> t)) => t
我以为实例中的类型签名会强制数字为Int,但它变成了Num a。为什么?如何让编译器识别出所有的数字都是整数?

类型类是开放的:稍后,可能在另一个模块中,您可以定义另一个实例。编译器不能依赖您不这样做,因此它无法提交到您迄今定义的实例

您可以在函数实例中尝试以下操作:

instance (Indexable r, a ~ Int) => Indexable (a -> r) where
  idx xs = \x -> idx (x:xs)
与Int->r的实例不同,此实例覆盖了整个函数空间a->r,但需要a~Int。这告诉编译器以后不能有任何其他形式为Char->r或类似的实例,因此允许编译器提前提交函数实例。

类型类打开:稍后,可能在另一个模块中,您可以定义另一个实例。编译器不能依赖您不这样做,因此它无法提交到您迄今定义的实例

您可以在函数实例中尝试以下操作:

instance (Indexable r, a ~ Int) => Indexable (a -> r) where
  idx xs = \x -> idx (x:xs)
与Int->r的实例不同,该实例覆盖了整个函数空间a->r,但需要a~Int。这告诉编译器以后不能有任何其他形式为Char->r或类似的实例,因此允许编译器提前提交函数实例