- Learning Rust
- Paul Johnson Vesa Kaihlavirta
- 220字
- 2021-07-02 23:07:25
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) }
推薦閱讀
- Oracle WebLogic Server 12c:First Look
- Django+Vue.js商城項目實戰
- Python數據分析入門與實戰
- Xcode 7 Essentials(Second Edition)
- The HTML and CSS Workshop
- Android底層接口與驅動開發技術詳解
- Learning Probabilistic Graphical Models in R
- 從Java到Web程序設計教程
- Java編程從入門到精通
- JavaScript+jQuery網頁特效設計任務驅動教程
- Python自然語言理解:自然語言理解系統開發與應用實戰
- Distributed Computing in Java 9
- Application Development with Parse using iOS SDK
- Visual Basic程序設計實驗指導及考試指南
- Mastering JavaScript Promises