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

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)  
} 
主站蜘蛛池模板: 晴隆县| 泾阳县| 车致| 普宁市| 文山县| 商水县| 星子县| 昌吉市| 云南省| 嘉祥县| 湟源县| 邓州市| 隆林| 东安县| 江源县| 靖宇县| 新密市| 昌吉市| 乌海市| 宜丰县| 永平县| 安泽县| 金山区| 涪陵区| 洪湖市| 昭通市| 云林县| 庆安县| 老河口市| 永登县| 黑山县| 鄂托克前旗| 华池县| 津南区| 拉孜县| 巴南区| 阳信县| 鄂伦春自治旗| 鹤峰县| 玉龙| 梁平县|