小编pml*_*mlt的帖子

如何比较递归数据结构?

我有一个复杂的递归数据结构,我已简化为以下内容:

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)

表达式ac在概念上是相同,但两者都代表保持该值1并指向表达式b的节点.我的问题是:如何在Haskell表达式中检查它们是否确实相等?如果我评估a == c它将继续永远评估循环结构中的子元素.

是否有可能在Haskell中执行这样的比较?

编辑:在我的情况下,我试图比较这两个用于检查/调试目的.但这样做的另一个原因可能是单元测试.

haskell

6
推荐指数
1
解决办法
568
查看次数

匹配没有参数列表的案例类

我注意到关于没有任何参数列表的案例类(不是案例对象)的非常奇怪的行为.在尝试对它们进行模式匹配时,似乎完全忽略了超类型.我写了一个小例子来展示行为:

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会这样做吗?

scala pattern-matching

3
推荐指数
1
解决办法
1031
查看次数

标签 统计

haskell ×1

pattern-matching ×1

scala ×1