casillas
casillas

Reputation: 16813

Recursive call in swift

I am confused with the following recursive example. The place where recursion happens, the local variable needs to be updated every time. I wonder then how it could store the base result? And let variable is not mutable, how it updates?

The question is as follows for the following solution:

Implement a recursive function named digits that takes a positive integer number and return an array containing it’s digits in order.

Function call:

digits(123)

Function output:

[1, 2, 3]

func digits(_ number:Int) -> [Int]
{
    if number >= 10 {
        // confusion in the following line
        let firstDigits = digits(number / 10)
        let lastDigit = number % 10
        return firstDigits + [lastDigit]
    } else {
        return [number]
    }
}

I would rather approach the problems as follows. I wonder what is the advantages of having the above solution.

func digits(_ number:Int) -> [Int]
{
    if number >= 10 {
        let lastDigit = number % 10
        return digits(number / 10) + [lastDigit]
    } else {
        return [number]
    }
}

Upvotes: 2

Views: 304

Answers (1)

Doug Richardson
Doug Richardson

Reputation: 10821

I wonder then how it could store the base result? And let variable is not mutable, how it updates?

firstDigits never changes, it is only set once in each invocation of digits. Each invocation of digits has it's own variables.

Example Execution

In the following example I show how the execute proceeds as a series of substitutions.

digits(123) ->
digits(123 / 10)  + [123 % 10] ->
digits(12)  + [3] ->
digits(12 / 10) + [12 % 10]  + [3] ->
digits(1) + [2] + [3] ->
[1] + [2] + [3] ->
[1, 2, 3]

Another way to write it that may be more clear

func digits(_ number:Int) -> [Int]
{
    if number >= 10 {
        return digits(number / 10) + [number % 10]
    } else {
        return [number]
    }
}

Upvotes: 5

Related Questions