Function 哈斯克尔不能';与预期类型不匹配,行为怪异
我有一个模块,如下所示:Function 哈斯克尔不能';与预期类型不匹配,行为怪异,function,haskell,Function,Haskell,我有一个模块,如下所示: module Network where import Prelude hiding ((==)) import Sort import Message data Pair = Conn Loc Loc | Disconn Loc Loc deriving(Show,Eq) data NC = EmpNC | Inn Pair NC instance Eq NC where EmpNC == EmpNC = True (Inn p nc1) == nc2 = (n
module Network where
import Prelude hiding ((==))
import Sort
import Message
data Pair = Conn Loc Loc | Disconn Loc Loc deriving(Show,Eq)
data NC = EmpNC | Inn Pair NC
instance Eq NC where
EmpNC == EmpNC = True
(Inn p nc1) == nc2 = (nc_include p nc2) && (nc1 == nc2)
_ == _ = False
nc_include::Pair->NC->Bool
nc_include p EmpNC = False
nc_include p1 (Inn p2 nc) = (p1 == p2) || (nc_include p1 nc)
instance Eq NC where -- make NC an instance of Eq with only default definitions
EmpNC == EmpNC = True -- define a new function (==) of type (NC -> NC -> Bool)
...
奇怪的是,对于我所说的最后一行(p1==p2),我无法将预期的类型NC与实际的类型对错误匹配。这意味着p1应该是NC而不是成对的。我不知道,你能帮我吗?
[Edit]隐藏(=)形式的前奏是因为无论我在哪里使用“==”操作符,我都会遇到无歧义错误。如果您也能提出更好的解决方案,我将不胜感激:D首先,这里是一个工作版本:
module Network where
data Loc = Loc deriving (Show, Eq)
data Pair = Conn Loc Loc | Disconn Loc Loc deriving(Show,Eq)
data NC = EmpNC | Inn Pair NC
instance Eq NC where
EmpNC == EmpNC = True
(Inn p nc1) == nc2 = (nc_include p nc2) && (nc1 == nc2)
_ == _ = False
nc_include :: Pair -> NC-> Bool
nc_include p EmpNC = False
nc_include p1 (Inn p2 nc) = (p1 == p2) || (nc_include p1 nc)
区别是什么(除了我随意定义的Loc
)?主要是格式化
我想发生的事情是这样的:
您试图为NC
编写Eq
的实例:
instance Eq NC where
EmpNC == EmpNC = True
...
并且意识到编译器不喜欢这个,说它与前奏曲中的(==)
冲突。但是,您从中得出了错误的结论,隐藏了前奏曲。(==)
并继续。现在,编译器没有抱怨,但它分析了您所做的如下操作:
module Network where
import Prelude hiding ((==))
import Sort
import Message
data Pair = Conn Loc Loc | Disconn Loc Loc deriving(Show,Eq)
data NC = EmpNC | Inn Pair NC
instance Eq NC where
EmpNC == EmpNC = True
(Inn p nc1) == nc2 = (nc_include p nc2) && (nc1 == nc2)
_ == _ = False
nc_include::Pair->NC->Bool
nc_include p EmpNC = False
nc_include p1 (Inn p2 nc) = (p1 == p2) || (nc_include p1 nc)
instance Eq NC where -- make NC an instance of Eq with only default definitions
EmpNC == EmpNC = True -- define a new function (==) of type (NC -> NC -> Bool)
...
这就是为什么现在您不能将(==)
应用于对
s,因为它的类型是(NC->NC->Bool)
,因此编译器告诉您它应该是NC
,而不是对
现在,问题的核心是实例定义遵循空白格式规则,因此您必须在实例中的函数前面至少保留一个空白列
定义:
instance Eq NC where
EmpNC == ...
工作,而
instance Eq NC where
EmpNC == ...
没有
其他一些事情也是如此,比如class
,do
,case
等等。为什么不键入NC=[Pair]
(尽管这不是所需的=
行为),或者newtype NC=NC{getNCPairs::[Pair]}
?隐藏的前奏是怎么回事?==
,你可能导入了一个坏的Eq
类吗?这是NC需要有这样的构造函数,我不认为这种声明会导致问题,是吗?哇!那会让我一生都明白!非常有用。