SML二叉树reduce函数
我收到了 SML 的作业,并且需要一些入门帮助。
问题是这样的
编写一个类型为“a btree ->”的函数 btree_size返回 int 二叉树的大小。 (二叉树的大小是 二叉树中的元素)。例如,btree_size(Node(Leaf, 1, Node (Leaf, 2, Leaf))) 应返回 2。您的函数必须使用 提供btree_reduce函数,最多3行。
btree_reduce 函数是这样的
(* A reduction function. *)
(* btree_reduce : ('b * 'a * 'b -> 'b) -> 'b -> 'a tree -> 'b) *)
fun btree_reduce f b bt =
case bt of
Leaf => b
| Node (l, x, r) => f (btree_reduce f b l, x, btree_reduce f b r)
我到底如何创建一个 btree_size 函数来获取 btree 并使用 reduce 函数来给出树的大小?
So I've got an assignment in SML and I need a bit of help getting started.
The problem goes like this
Write a function btree_size of type 'a btree -> int that returns the
size of the binary tree. (The size of a binary tree is the number of
elements in the binary tree). For example, btree_size (Node (Leaf, 1,
Node (Leaf, 2, Leaf))) should return 2. Your function must use the
provided btree_reduce function and should be at most 3 lines long.
The btree_reduce function is this
(* A reduction function. *)
(* btree_reduce : ('b * 'a * 'b -> 'b) -> 'b -> 'a tree -> 'b) *)
fun btree_reduce f b bt =
case bt of
Leaf => b
| Node (l, x, r) => f (btree_reduce f b l, x, btree_reduce f b r)
How in the world do I make a btree_size function that takes a btree and uses the reduce function to give me the size of the tree?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于这是一项作业,我不会直接给出答案。 :)
我将按照以下步骤进行:
当然,这是众多方法之一。
Since this is a homework, I will refrain from giving direct answers. :)
I'd proceed as follows:
This is one of the many ways, of course.