我有一个复杂的递归数据结构,我已简化为以下内容:
data Node = Node { value :: Integer, next :: Node } deriving (Show,Eq)
Run Code Online (Sandbox Code Playgroud)
给出以下表达式:
--Create a circular structure
a = Node 1 b
b = Node 0 a --Tie the knot
c = Node 1 b --Another structure which points to b
Run Code Online (Sandbox Code Playgroud)
表达式a和c在概念上是相同,但两者都代表保持该值1并指向表达式b的节点.我的问题是:如何在Haskell表达式中检查它们是否确实相等?如果我评估a == c它将继续永远评估循环结构中的子元素.
是否有可能在Haskell中执行这样的比较?
编辑:在我的情况下,我试图比较这两个用于检查/调试目的.但这样做的另一个原因可能是单元测试.
我注意到关于没有任何参数列表的案例类(不是案例对象)的非常奇怪的行为.在尝试对它们进行模式匹配时,似乎完全忽略了超类型.我写了一个小例子来展示行为:
object TestMatch {
trait CommonType
case class A(val x:Int) extends CommonType
case class B extends CommonType
case object C extends CommonType
def main(args: Array[String]): Unit = {
printifmatched(A(1))
printifmatched(B)
printifmatched(C)
}
def printifmatched: PartialFunction[Any,Unit] = {
case x: CommonType => println("This is a common type", x)
case x => println("This is not a common type", x)
}
}
Run Code Online (Sandbox Code Playgroud)
该程序的输出如下:
(This is a common type,A(1))
(This is not a common type,B)
(This is a common type,C)
Run Code Online (Sandbox Code Playgroud)
这是一个错误吗?任何人都可以解释为什么Scala会这样做吗?