Processing Collections of Items Using Functional Language Features
Sources
https://doc.rust-lang.org/book/ch13-00-functional-features.html
https://rust-unofficial.github.io/patterns/functional/index.html
Rust provides many functional language features, and the most popular usage is when processing a
collection of items. Some example methods are
fold()
,
filter()
,
map()
,
reduce()
, etc.
The following uses an imperative programming style to calculate a sum.
fn main() { let mut sum = 0; for i in 1..11 { sum += i; } println!("{}", sum); }
We can accomplish the same task using fold()
. The method signature of fold()
looks like the
following.
#![allow(unused)] fn main() { fn fold<B, F>(self, init: B, f: F) -> B where F: FnMut(B, Self::Item) -> B }
The first parameter is an initial value. The second parameter f
takes a closure which is an
anonymous function or a lambda function in Rust. The syntax for a closure is |param1, param2, ...| { function body }
. If the function body is a single line, you can omit {}
, i.e., |param1, param2, ...| single_line_function_body
. In case of fold()
there should be two parameters for the
closure, e.g., it.fold(init, |acc, x| { /* function body */ });
.
This means that fold()
can be called on an iterator, and it takes two arguments---one is the
initial value and the other is a closure. fold()
first takes the initial value and the
first item in the iterator. Using those as arguments, fold()
calls the closure. From
there, fold()
iterates---it takes the result of the closure from the previous iteration as
well as the next item in the iterator, and calls the closure again using those as arguments. It
returns the final result from the final call to the closure. Thus, the following code calculates a
sum.
fn main() { println!("{}", (1..11).fold(0, |a, b| /* function body */ )); }