官术网_书友最值得收藏!

Recursive functions

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)  
} 
主站蜘蛛池模板: 长兴县| 合川市| 普定县| 彭水| 永靖县| 大田县| 米泉市| 邵武市| 六枝特区| 衢州市| 应城市| 都江堰市| 杭州市| 西充县| 德令哈市| 凤台县| 祁东县| 伊宁县| 沙田区| 宿松县| 汪清县| 云梦县| 万载县| 思茅市| 南丹县| 洪江市| 宜兰县| 红桥区| 遵义市| 远安县| 滁州市| 吴桥县| 西乌| 定结县| 内江市| 威远县| 左权县| 阿合奇县| 安岳县| 封开县| 天台县|