开发者

SML binary tree reduce function

开发者 https://www.devze.com 2023-02-11 18:44 出处:网络
So I\'ve got an assignment in SML and I need a bit of help getting started. The problem goes like this

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 lin开发者_如何学JAVAes 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?


Since this is a homework, I will refrain from giving direct answers. :)

I'd proceed as follows:

  • get acquainted with computing the size of the tree (by writing a recursive function which meets your specification)
  • see what is common between the function you wrote and btree_reduce (or, what could be abstracted out from the function you wrote)

This is one of the many ways, of course.

0

精彩评论

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

关注公众号