Recursionis the programming technique of calling a function within that same function.Tail recursionis an optimization that can be explicitly applied to some recursive functions.

A recursive task refers to the previous result. Factorials are a common example—`factorial(n)`

multiplies all numbers from `1`

to `n`

, and can be defined like this:

`factorial(1)`

is`1`

`factorial(n)`

is`n * factorial(n - 1)`

`factorial()`

is recursive because it uses the result from the same function applied to its modified argument. It’s easy to implement the logic for `factorial()`

:

```
// Recursion/Factorial.kt
package recursion
import atomictest.eq
fun factorial(n: Long): Long {
if (n <= 1) return 1
return n * factorial(n - 1)
}
fun main(args: Array<String>) {
factorial(5) eq 120
factorial(17) eq 355687428096000
}
```

This recursive definition is easy to read, but it’s also expensive.

**End of sample. See AtomicKotlin.com for full early-access book.**

Previous Next

©2018 Mindview LLC. All Rights Reserved.