如何进行此 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
我认为我必须使用map... 我尝试了这个,但有 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));
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),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));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你有两个地方做错了。首先,
nil
不是stree
,但Brnch nil
是stree
。其次,lst
不是一个 stree,但Brnch lst
是一个stree
。您的函数可以按如下方式更正(为了可读性,我重新排序了案例):另一件事是,您应该按照数据类型的结构编写函数。所以使用
List
函数的以下版本更好:There are two spots where you did wrong. First of all,
nil
is not astree
butBrnch nil
is astree
. Second,lst
is not a stree butBrnch lst
is astree
. Your function can be corrected as follows (I reorder cases for readability):One more thing, you should write your function following the structure of the datatype. So the following version using
List
functions is better: