2014-03-04 102 views
0

我正在爲SML中的Programming Languages類做簡單的練習,練習是計算樹是否平衡。下面的代碼是什麼,我認爲將是一個有效的解決方案: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類型,爲什麼不工作?

回答

3

我沒有一個SML編譯器現在,所以我不能對此進行測試,但嘗試改變balanced(n1)(balanced (NODE n1))(同樣與balanced(n2))