开发者

How to make this ml procedure

开发者 https://www.devze.com 2023-03-09 17:05 出处:网络
I have this code: datatype \'a tree = Leaf of \'a | Node of \'a * \'a tree * \'a tree | Nil; val rec tree_sum = fn(f,e,Nil) => e

I have this code:

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)开发者_如何学C,Node(2,Leaf(1),Node(8,Nil,Nil)));
tree_sum((fn(a,b,c)=> a+b+c),0,binnum);
val it = 20 : int

How can I do the same procedure treesum when i have another datatype which is:

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

I think that i have to use map... I try this but there are 3 errors

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));


There are two spots where you did wrong. First of all, nil is not a stree but Brnch nil is a stree. Second, lst is not a stree but Brnch lst is a stree. Your function can be corrected as follows (I reorder cases for readability):

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));

One more thing, you should write your function following the structure of the datatype. So the following version using List functions is better:

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;
0

精彩评论

暂无评论...
验证码 换一张
取 消