2013-10-20 55 views
0

我有一個數據類型:如何在SML中使用模式匹配(如趣味)創建匿名函數?

datatype 'a tree = LEAF of 'a 
      | NODE of 'a tree * 'a tree; 

我想創建一個名爲maptree(F)函數,它能夠返回頒佈F元素明智的一棵樹的匿名函數。爲什麼以下不起作用?

fun maptree(f) = fn LEAF(a) => LEAF(f(a)) 
        | NODE((b,c)) => NODE(f(b), f(c)); 

我得到的錯誤:

stdIn:56.7-56.65 Error: types of rules don't agree [circularity] 
earlier rule(s): 'Z tree tree -> 'Y tree tree 
this rule: 'Z tree -> 'Y tree 
in rule: 
NODE (b,c) => NODE (f b,f c) 

回答

3
f : 'a -> 'b 

,所以你不能把它應用到一棵樹。你可能想要。

fun maptree f = fn LEAF a => LEAF (f a) 
       | NODE(b,c) => NODE (maptree f b, maptree f c);