Update Examples
parent
c6c4ba37cd
commit
fbb4a91b52
51
Examples.md
51
Examples.md
@ -1283,11 +1283,62 @@ fn main
|
|||||||
<td>
|
<td>
|
||||||
|
|
||||||
```
|
```
|
||||||
|
fn is_odd(n: u32) -> bool {
|
||||||
|
n % 2 == 1
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let upper = 1000;
|
||||||
|
|
||||||
|
// Imperative approach
|
||||||
|
let mut acc = 0;
|
||||||
|
for n in 0.. {
|
||||||
|
let n_squared = n * n;
|
||||||
|
|
||||||
|
if n_squared >= upper {
|
||||||
|
break;
|
||||||
|
} else if is_odd(n_squared) {
|
||||||
|
acc += n_squared;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
println!("imperative style: {}", acc);
|
||||||
|
|
||||||
|
// Functional approach
|
||||||
|
let sum_of_squared_odd_numbers: u32 =
|
||||||
|
(0..).map(|n| n * n)
|
||||||
|
.take_while(|&n_squared| n_squared < upper)
|
||||||
|
.filter(|&n_squared| is_odd(n_squared))
|
||||||
|
.sum();
|
||||||
|
println!("functional style: {}", sum_of_squared_odd_numbers);
|
||||||
|
}
|
||||||
```
|
```
|
||||||
</td><td>
|
</td><td>
|
||||||
|
|
||||||
```
|
```
|
||||||
|
// The below will actually make a closure that captures nothing, not a function as on the left; do we care?
|
||||||
|
let is_odd = $ % 2 == 1
|
||||||
|
|
||||||
|
fn main
|
||||||
|
let upper = 1000
|
||||||
|
|
||||||
|
// Imperative approach
|
||||||
|
let mut acc = 0
|
||||||
|
for n in 0..
|
||||||
|
let n_squared = n * n
|
||||||
|
|
||||||
|
if n_squared >= upper then break
|
||||||
|
else if is_odd n_squared
|
||||||
|
acc += n_squared
|
||||||
|
|
||||||
|
println! "imperative style: {}", acc
|
||||||
|
|
||||||
|
// Functional approach
|
||||||
|
let sum_of_squared_odd_numbers: u32 =
|
||||||
|
(0..).map $ * $
|
||||||
|
.take_while $ < &upper
|
||||||
|
.filter is_odd *$
|
||||||
|
.sum()
|
||||||
|
println! "functional style: {}", sum_of_squared_odd_numbers
|
||||||
|
|
||||||
```
|
```
|
||||||
</td></tr></table>
|
</td></tr></table>
|
||||||
|
Loading…
Reference in New Issue
Block a user