在SML中键入模式匹配

时间:2014-03-04 02:47:57

标签: sml

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

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类型,为什么这不起作用?

1 个答案:

答案 0 :(得分:3)

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