3 unstable releases
0.2.0 | Jan 18, 2021 |
---|---|
0.1.1 | Jan 14, 2021 |
0.1.0 | Jan 14, 2021 |
#1561 in Algorithms
7KB
94 lines
unfold
A simple unfold implementation in Rust
unfold let you create an iterator that, staring from a given initial value, applies a given function to the current state, store the result for the next iteration, and return the current state.
Unfold defines an endless iterator: you must stop it by hand, like in the example.
Example
use unfold::Unfold;
// Create a vector containing the first 5 numbers from the Fibonacci
// series
let fibonacci_numbers: Vec<u64> = Unfold::new(|(a, b)| (b, a + b), (0, 1))
.map(|(a, _)| a)
.take(5) //Unfold iterator never stops.
.collect();
assert_eq!(vec![0, 1, 1, 2, 3], fibonacci_numbers);
lib.rs
:
unfold
The unfold function takes as input a function f and an initial i value and returns a list defined as [i, f(i), f(f(i)), ...].
This library defines Unfold
a struct
that implements the unfold function as an endless
iterator.
Quick Start
To use Unfold
is quite simple. The user calls
the new function providing a function as first argument
and the initial value as second argument.
An Unfold
instance can be then used as any iterator,
but don't forget: Unfold never ends, it must be stopped.
Here an example:
use unfold::Unfold;
// Create a vector containing the first 5 numbers from the Fibonacci
// series
let fibonacci_numbers: Vec<u64> = Unfold::new(|(a, b)| (b, a + b), (0, 1))
.map(|(a, _)| a)
.take(5) //Unfold iterator never stops.
.collect();
assert_eq!(vec![0, 1, 1, 2, 3], fibonacci_numbers);