简体   繁体   中英

Defining the Accumulator of a Tail Recursive Function in F#

I am a beginner in F#, and I am still having trouble wrapping my head around the concept of the tail recursion. Specifically, I do not know how tail recursion works since neither is there any value associated with the accumulator, nor is the accumulator ever defined.

Here is some sample code for a tail recursive function for computing a factorial

let factorial x =
// Keep track of both x and an accumulator value (acc)
    let rec tailRecursiveFactorial x acc =
        if x <= 1 then 
            acc
        else 
            tailRecursiveFactorial (x - 1) (acc * x)
    tailRecursiveFactorial x 1

I am not asking for how to write a tail recursive function, nor am I asking for examples of tail and non-tail recursive functions. What I am asking is how the accumulator works since it is never defined

The accumulator is defined here:

let rec tailRecursiveFactorial x acc =

This local function has the type int -> int -> int , which means that acc has type int .

The compiler infers this because x is compared to the literal 1 , which is of the type int , because it's an unqualified integer literal. This means x must be of the type int as well.

Likewise, the expression acc * x makes use of x , and the compiler then infers that acc must have the type int as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM