The usual recursive formulation of the function that computes the sum of a tree
let rec sum_tree t =
match t with
| Leaf -> 0
| Node (l, x, r) -> sum_tree l + x + sum_tree r
is not tail-recursive.
For a tail recursive implementation, you may need to use an auxiliary function of type
aux: int -> int tree list -> int
Hint: aux acc ts takes as input an accumulator acc as usual and a list of sub-trees obtained from the input tree. The idea is that when the list is empty, acc is the sum of all input-tree elements. Implement a tail recursive function sumtailrec that uses this idea.
sumtailrec: int tree -> int
Your solution must be strictly tail-recursive. The following solution sums all nodes on the left branch l and then all nodes on the right branch r is incorrect. Calling the aux function twice in the recursive code makes the function not tail-recursive because you need a stack frame for the first call. You should only call the aux function once in the recursive code. Following the hint above can correct this solution.
let rec aux (acc:int) (ts: int tree) =
match ts with | Leaf -> acc
| Node(l, x, r) -> (aux (aux (acc+x) l)) r
In [ ]:
let sumtailrec t =
(* YOUR CODE HERE *)
In [ ]:
let tree = construct [2;1;3] in
assert (sumtailrec tree = sum_tree tree)

Answers

Answer 1

If construct builds a binary search tree from a list of integers, the assertion should pass.

How to implement a tail-recursive function to compute the sum of a tree data structure?

Here's a possible implementation of the sumtailrec function in a tail-recursive way using the aux function suggested:

type 'a tree = Leaf | Node of 'a tree * 'a * 'a tree

let sumtailrec t =

 let rec aux acc ts_stack =

   match ts_stack with

   | [] -> acc

   | Leaf :: ts' -> aux acc ts'

   | Node (l, x, r) :: ts' -> aux (acc + x) (l :: r :: ts')

 in

 aux 0 [t]

The aux function takes an accumulator acc and a stack of trees ts_stack. The stack initially contains only the input tree t.

In each iteration, it pops a tree ts from the top of the stack, and if ts is a leaf, it continues with the next tree on the stack.

If ts is a node, it adds its value to the accumulator acc and pushes its left and right subtrees onto the stack. The function returns acc when the stack is empty.

The sumtailrec function simply calls aux with an initial accumulator of 0 and a stack containing the input tree t. Finally, it returns the result of aux.

The function construct used in the test case is not defined, so I cannot test the function, but if construct builds a binary search tree from a list of integers, the assertion should pass.

Learn more about implement a tail-recursive function.

brainly.com/question/30020618

#SPJ11


Related Questions

Other Questions
10. During which part of the sleep cycle should you aim to wake up? A. In the middle of the nREM stageO B. At the beginning C. At the end D. In the middle of the REM stage which strategy in the ansoff's product-market growth matrix combines current markets and new products? a.market development b.product development c.diversify d.market penetration In Problems 1-4, use the method of undetermined coefficients to determine the form of a particular solution for the given equation. 1. y"' 2y" 5y' + 6y = e^x + x^2 2. y"' + y" 5y' + 3y = e^-x +sinx 3. y"' + 3y" 4y = e^-2x Watters Umbrella Corp. issued 10-year bonds three years ago at a coupon rate of 10.7 percent. The bonds make semiannual payments. If these bonds currently sell for 134.4 percent of par value, what is the YTM? (Do not round intermediate calculations. Round the final answer to 2 decimal places.) YTM 9 Can someone help me asap? Its due today!! I will give brainliest if its correctPlease show work After the fission of U-235 takes place, how many neutrons does the missing nucleushave (don't forget to include ALL the neutrons, to include the ones that are just ontheir own)?14484235141 The Mysteries is a taped live performance-True-False W. Q. 2: The stars Betelgeuse and Rigel are both in the constellation Orion. Betelgeuse appears red in color and Rigel in bluish white. To the eye, the two stars appear almost equally bright. If you can compare the temperature, luminosity, or size from just this information, do so. If not, explain why. increasing gnp is a necessary but not a sufficient condition for improving living standards in less developed countries. true or false, explain. Which one of the following countries dominated world production of steel and textiles during the nineteenth century?A) United KingdomB) GermanyC) FranceD) United StatesE) Russia Use plate tectonic theory to explain the origin of the Andes Mountains. In your answer, include a discussion ofa. the plate tectonic process involvedb. -the plate boundaryc. the composition of the rocks found there based on the rock cycle.d. the type of eruptions that occur theree. other geologic features associated with Andes-type mountains. Find the answer using long polynomial division to lock the kernel on a single processor machine in linux, kernel preemption is disabled.true or false which of teh following statements about viruses is more accurate? wiruses can reproduce rapidly on surfaces outside the body, viruses contain no dna or rna of their own; thereforem they must enter a host cell to obtain a nucleic acis Simplify. Assume variables equal zero. What are some of the reasons major recent earthquakes have had large death tolls?structural collapse of poorly built structuresgeneration of damaging tsunamilocation near high population densitiesall of these list the factors that influence the energy losses and thus theefficiency of solar cellsplease type An Air Force plane left Paris and flewsouth at an average speed of 240 km/h.cargo plane left sometime later flying inthe opposite direction with an averagespeed of 155 km/h. After the Air Forceplane had flown for 11 hours the planeswere 3570 km apart. How long did thecargo plane fly? Consider the reaction:CaCO3(s)CaO(s)+CO2(g)Using standard thermodynamic data at 298 K, calculate the entropy change for the surroundings when 2.36 moles of CaCO3(s) react at standard conditions. What is DisHumanism and DisHumanism?