10.1.1.1 using the accumulator parameter

Source: Internet
Author: User

10.1.1.1 using the accumulator parameter

Let's consider how to change the Sumlist function to tail recursion, that is, to perform a recursive call only on the branch where the parameter value is the Cons cell (not the empty list). Our rule of thumb suggests that it shouldn't be difficult, but for now, it does more than just return the result of a recursive call: The value in the head is added to the sum.

To turn this function into a tail-recursive function, you can use the method that provides the accumulator parameter (accumulator argument). When the result is calculated, no longer jumps from right to left (in the previous diagram, back to the original function call), and the computed result as part of the run operation before the recursive call. We need to add another parameter to the function that provides the current result. Listing 10.2 shows this approach.

Listing 10.2 sumlist functions for tail recursion (F # Interactive)

> Let rnd = new System.Random ()

Let test1 = List.init 10000 (fun _, Rnd). Next (-50, 51)) | [1]

Let test2 = List.init 100000 (fun _, Rnd).   Next (-50, 51);; |

Val Rnd:random

val test1:int list = [1;-14;-35; 34;-1;-39; ....]

val test2:int list = [29;-44;-1; 25;-33; 36; ....]

> Let sumlist (LST) =

Let Recsumlistutil (LST, total) = [2]

Match LST with

| [] Total [3]

|hd::tl–>

Letntotal = HD + total [4]

Sumlistutil (TL, ntotal) <--for recursive invocation

Sumlistutil (lst,0); <--calling auxiliary functions with total = 0

Val sumlist:int list–> int

> sumlist (test1); |

Val It:int =–2120 | Called two times

| Calculation results

> sumlist (test2); |

Val It:int = 8736 |

Listing 10.2 Mr. First into two lists containing a random number [1]. We use the List.init function, which takes the length of the list requirement as the first parameter value, invokes the provided function, and calculates the value of the element at the specified index. We did not use the index during the calculation, so we ignored it with "_". The reason we need a better test input, if we calculate all the numbers between 1 and 100,000, will get incorrect results because, the result is more than 32-bit integers. We generate random numbers between –50 and 50, so, in principle, the sum of the calculations should be very close to zero.

The most important part of the list is the Sumlist function. When you use the accumulator parameter, you also need to write a function that has an additional parameter. We don't usually want the caller to see this parameter, so take it as a local function [2]; the accumulator parameter (in the example, total) saves the current result. When the end of the list is reached, the result is there, so just return it [3]; otherwise, the value in the head is added to the result, the accumulator is set to the new value [4], and then the recursive call is performed. Figure 10.4 shows how the new calculation model works. Whether you invoke a tool function or call an internal recursive function, the result is returned immediately, so you can run with a tail call.

Figure 10.4 Running the tail recursive function sumlist. For the first time, the tool function is called, tracking the current result, and using the accumulator parameter (total) to calculate the and of all preceding elements.

The sumlist example is not difficult and demonstrates the principle of using accumulators. Adds another parameter to the function that is used to calculate the temporary result before a recursive call is made. The intention is to change the function to tail recursion, to find out the current information that is used after the recursive call, and try to pass it to the recursive call.

When we talk about list processing, we'll see a more skillful example, and now we'll start by discussing another important optimization method: Memory (memoization, cache function return value).

10.1.1.1 using the accumulator parameter

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.