我有一个看起来像这样的模块:
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)
Run Code Online (Sandbox Code Playgroud)
奇怪的部分是我得到的无法匹配期望类型NC与我说的最后一行的实际类型对错误(p1 == p2).意味着p1应该是NC而不是Pair.我不在乎,你能帮忙吗? [编辑] 隐藏(==)形式前奏的事情是因为无论我有什么"=="运算符,我都会出现混淆错误.如果您也建议更好的解决方案,我将不胜感激:D
fir*_*dle 12
首先,这是一个工作版本:
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)
Run Code Online (Sandbox Code Playgroud)
有什么区别(除了我的任意定义Loc)?主要是格式化.
我想发生的事情是这样的:
您试图编写Eqfor 的实例NC:
instance Eq NC where
EmpNC == EmpNC = True
...
Run Code Online (Sandbox Code Playgroud)
并实现了编译器不喜欢这个,称它与冲突(==)从Prelude.但是,你从中得出了错误的结论,隐藏Prelude.(==)和继续.现在编译器没有抱怨,但它解析了你这样做:
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)
...
Run Code Online (Sandbox Code Playgroud)
这就是为什么现在你不能适用(==)于PairS,因为它的类型(NC -> NC -> Bool),因此编译器会告诉你,这本来期望的NC,而不是一个Pair.
现在,问题的核心是实例定义遵循空格格式规则,因此您必须在instance定义中的函数之前留下至少一个空格列:
instance Eq NC where
EmpNC == ...
Run Code Online (Sandbox Code Playgroud)
工作,而
instance Eq NC where
EmpNC == ...
Run Code Online (Sandbox Code Playgroud)
没有.
这同样适用于一些其他的东西像真正的class,do,case等.
| 归档时间: |
|
| 查看次数: |
183 次 |
| 最近记录: |