如何制作这个ml程序

时间:2011-05-30 03:56:46

标签: tree sml ml

我有这段代码:

datatype 'a tree = Leaf of 'a | Node of 'a * 'a tree * 'a tree | Nil;
val rec tree_sum = fn(f,e,Nil) => e 
                   | (f,e,Leaf(n)) => n 
                   | (f,e,Node(node,right,left)) =>     
                               f(node,tree_sum(f,e,right),tree_sum(f,e,left));

val binnum = Node(5,Leaf(4),Node(2,Leaf(1),Node(8,Nil,Nil)));
tree_sum((fn(a,b,c)=> a+b+c),0,binnum);
val it = 20 : int

当我有另一种数据类型:

时,如何执行相同的过程treesum
datatype 'a stree = Leaf of 'a | Brnch of 'a stree list;

treesum(fn(a, b) => a + b, 0, Brnch([Leaf 2, Brnch([Leaf 5, Leaf 3, Leaf 8])]));
val it = 18 : int

我认为我必须使用地图...... 我试试这个,但有3个错误

val rec treesum = 
         fn (f,e,nil) => e 
            | (f,e,Leaf(n)) => n 
            | (f,e,Brnch(h::lst)) => 
                   f(treesum(f,e,h),treesum(f,e,lst));

1 个答案:

答案 0 :(得分:1)

有两个地方你做错了。首先,nil不是streeBrnch nilstree。其次,lst不是stree,但Brnch lststree。您的功能可以按如下方式更正(我为可读性重新排序):

val rec treesum = 
         fn (f,e,Leaf(n)) => n 
            | (f,e,Brnch nil) => e 
            | (f,e,Brnch(h::lst)) => 
                   f(treesum(f,e,h),treesum(f,e,Brnch lst));

还有一件事,你应该按照数据类型的结构编写你的函数。因此,使用List函数的以下版本更好:

val rec treesum = 
         fn (f,e,Leaf(n)) => n 
            | (f,e,Brnch ls) => 
                   List.foldl (fn (l, acc) => f(treesum(f,e,l), acc)) e ls;