【问题标题】:Type pattern matching in SMLSML 中的类型模式匹配
【发布时间】:2014-03-04 11:15:34
【问题描述】:

我正在为 SML 中的编程语言类做一个简单的练习,练习是计算一棵树是否平衡。以下代码是我认为有效的解决方案:

datatype IntTree = LEAF of int | NODE of (IntTree * IntTree);

fun balanced (LEAF l) = true 
  | balanced (NODE (LEAF l, NODE n)) = false
  | balanced (NODE (NODE n1, NODE n2)) = balanced(n1) andalso balanced(n2)
  | balanced (NODE (NODE n, LEAF l)) = false
  | balanced (NODE (LEAF l1, LEAF l2)) = true;

但是,当我尝试在解释器中运行它时,出现以下错误:

stdIn:98.42-98.54 Error: operator and operand don't agree [tycon mismatch]
  operator domain: IntTree
  operand:         IntTree * IntTree
  in expression:
    balanced n1
stdIn:98.63-98.75 Error: operator and operand don't agree [tycon mismatch]
  operator domain: IntTree
  operand:         IntTree * IntTree
  in expression:
    balanced n2

但是NODE 应该是IntTree 类型,为什么这不起作用?

【问题讨论】:

    标签: sml


    【解决方案1】:

    我现在没有 SML 编译器,因此无法对此进行测试,但请尝试将 balanced(n1) 更改为 (balanced (NODE n1))(与 balanced(n2)) 相同。

    【讨论】:

      猜你喜欢
      • 2010-12-20
      • 1970-01-01
      • 2017-06-10
      • 1970-01-01
      • 2023-04-05
      • 2021-06-01
      • 2018-10-05
      • 2023-03-08
      • 1970-01-01
      相关资源
      最近更新 更多