Higher-order Functions: Rust's Secret Sauce
Get introduced to higher-order functions and functional programming.
Higher-order functions
Higher-Order Functions (HOF) are the Higher-order functions (HOF) represent the third fundamental block of functional programming after closures and iterators. We can consider HOFs to be the glue between the other two.
HOFs are functions that take other functions as arguments and, optionally, can return functions.
HOFs can take many forms. Here’s an example with a single argument and function return, with generics in place:
fn hof<A, B>(fun: Fn(A) -> B) -> Box<Fn(A) -> B >
Again, this is just a generic example.
Let’s take a look at HOFs at work in some concrete applications.
Functions as parameters
Let’s say we want to take a function as a parameter:
fn hof<F> (normal_argument: i32, function_argument: F) -> i32where F: Fn(i32) -> i32 {function_argument(normal_argument)}
In the code above, we define the function hof
that takes a normal argument (an i32
) and an argument F
, which we define later with where
. This is one of the perks of Rust.
In the body of the function, we pass the normal argument to the function argument.
This is possible because the function argument takes an i32
as an argument and returns an i32
that we can immediately return from our hof
function.
Now, let’s try using our function:
fn add_one (p: i32) -> i32 {p + 1}println!("{}", hof(5, add_one));
As you can see, we have created the classic add_one
function, which sums 1
to its parameter, and passes it to our hof
...