The final form of loop to consider is known as a recursive function. This is a function that calls itself until a condition is met. In pseudocode, the function looks like this:
float my_function(i32:a: i32) { // do something with a if (a != 32) { my_function(a); } else { return a; } }
An actual implementation of a recursive function would look like this:
// 04/recurse-1/src/main.rs
fn recurse(n: i32) { let v = match n % 2 { 0 => n / 2, _ => 3 * n + 1 }; println!("{}", v); if v != 1 { recurse(v) } } fn main() { recurse(25) }
The idea of a recursive function is very simple, but we need to consider two parts of this code. The first is the let line in the recurse function and what it means:
let v = match n % 2 { 0 => n / 2, _ => 3 * n + 1 };
Another way of writing this is as follows:
let mut v = 0i32; if n % 2 == 0 { v = n / 2; } else { v = 3 * n + 1; }
The second part is that the semicolon is not being used everywhere. Consider the following example:
fn main() { recurse(25) }