- 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) }
推薦閱讀
- Flask Web全棧開(kāi)發(fā)實(shí)戰(zhàn)
- Learn TypeScript 3 by Building Web Applications
- 算法零基礎(chǔ)一本通(Python版)
- Web Scraping with Python
- 架構(gòu)不再難(全5冊(cè))
- 深入淺出Prometheus:原理、應(yīng)用、源碼與拓展詳解
- HTML5+CSS3基礎(chǔ)開(kāi)發(fā)教程(第2版)
- Ray分布式機(jī)器學(xué)習(xí):利用Ray進(jìn)行大模型的數(shù)據(jù)處理、訓(xùn)練、推理和部署
- Learning Laravel 4 Application Development
- TypeScript實(shí)戰(zhàn)指南
- JavaScript動(dòng)態(tài)網(wǎng)頁(yè)開(kāi)發(fā)詳解
- Mastering Rust
- Modern JavaScript Applications
- C#程序設(shè)計(jì)
- PHP 7+MySQL 8動(dòng)態(tài)網(wǎng)站開(kāi)發(fā)從入門(mén)到精通(視頻教學(xué)版)