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 尝试定义新类型的实例时出现不明确的错误_Haskell - Fatal编程技术网

Haskell 尝试定义新类型的实例时出现不明确的错误

Haskell 尝试定义新类型的实例时出现不明确的错误,haskell,Haskell,我有以下代码 newtype MyList a = MyList { getList :: [a] } deriving Show instance Functor MyList where fmap f x = MyList (fmap f (getList x)) 并获取以下错误: 它可以指从以下位置的“Prelude”导入的“Prelude.fmap” compile.hs:1:1(最初在'GHC.Base'中定义)或'Main.fmap', 在编译时定义。hs:6:1 如果我理解正确

我有以下代码

newtype MyList a = MyList { getList :: [a] } deriving Show

instance Functor MyList where
fmap f x = MyList (fmap f (getList x))
并获取以下错误:

它可以指从以下位置的“Prelude”导入的“Prelude.fmap” compile.hs:1:1(最初在'GHC.Base'中定义)或'Main.fmap', 在编译时定义。hs:6:1


如果我理解正确的话。是我为新类型创建的新实例如何影响列表[]类型的现有实例。但为什么会这样?我认为newtype的目标是为同一类型创建一个不同的实例,这是一个缩进错误。代码应改为:

newtype MyList a = MyList { getList :: [a] } deriving Show

instance Functor MyList where
    fmap f x = MyList (fmap f (getList x))

不,您的实例不会“替换”或以其他方式影响常规列表实例。这只是语法上的混乱

Haskell语法对缩进很敏感。特别是,类实例成员应该相对于单词
instance
进一步向右缩进,如下所示:

instance Foo Bar where
    foo = ...
instance Functor MyList where
    fmap f x = ...
但是,在您的情况下,
fmap
的定义不是这样缩进的。编译器认为这意味着您正在声明一个“空”实例
Functor MyList
(其中“空”的意思是“不定义任何方法”-这在技术上是合法的),然后,在该实例之后,单独定义一个名为
fmap
的函数

由于Prelude中已经定义了一个同名函数,因此当您试图调用它时,编译器不知道选择哪一个-因此出现了错误

要解决此问题,只需将
fmap
定义缩进右侧,如下所示:

instance Foo Bar where
    foo = ...
instance Functor MyList where
    fmap f x = ...

(和往常一样,完全写出显式分隔符
{;}
这一不受欢迎的选项本来可以防止这个错误……)