Programming-Idioms

History of Idiom 31 > diff from v58 to v59

Edit summary for version 59 :
[Rust] Added an online demo

Version 58

2020-07-02, 15:02:29

Version 59

2020-07-02, 15:04:43

Idiom #31 Recursive factorial (simple)

Create recursive function f which returns the factorial of non-negative integer i, calculated from f(i-1)

Idiom #31 Recursive factorial (simple)

Create recursive function f which returns the factorial of non-negative integer i, calculated from f(i-1)

Variables
f,i
Variables
f,i
Code
fn factorial(num: u64) -> u64 {
    match num {
        0 | 1 => 1,
        _ => factorial(num - 1) * num,
    }
}
Code
fn factorial(num: u64) -> u64 {
    match num {
        0 | 1 => 1,
        _ => factorial(num - 1) * num,
    }
}
Comments bubble
match arm for 0|1 checks if the numbers are either 0 or 1
Comments bubble
match arm for 0|1 checks if the numbers are either 0 or 1
Doc URL
https://doc.rust-lang.org/book/ch18-03-pattern-syntax.html#multiple-patterns
Doc URL
https://doc.rust-lang.org/book/ch18-03-pattern-syntax.html#multiple-patterns
Demo URL
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=b0e7835b67a66d41783d3dc15fdfc74e