IterFi

Trait IterFi 

Source
pub trait IterFi: Iterator {
    // Provided methods
    fn iter_if<C, T: Iterator>(
        self,
        condition: bool,
        func: C,
    ) -> IterIf<T, Self> 
       where Self: Sized,
             C: Fn(Self) -> T { ... }
    fn map_if<C, T>(
        self,
        condition: bool,
        func: C,
    ) -> IterIf<Map<Self, C>, Self> 
       where Self: Sized,
             C: Fn(Self::Item) -> T { ... }
}
Expand description

Boolean composable iterators.

This trait adds the iter_if method which takes a boolean condition and a function. If the condition is met, the function is run and the returned iterator is used as output. Otherwise, the call is ignored and the original iterator continues.

This trait has an automatic blanket implementation for all Iterators. You do not need to implement it on your own iterators.

Provided Methods§

Source

fn iter_if<C, T: Iterator>(self, condition: bool, func: C) -> IterIf<T, Self>
where Self: Sized, C: Fn(Self) -> T,

If condition is true, return the iterator returned by func. Otherwise, skip this call and return self.

Note that if T::Item is not the same as F::Item, you will need to call branched after this to get an iterator.

§Examples

When the condition is true, the function is applied:

use iter_fi::IterFi;

let numbers = (0..5).iter_if(true, Iterator::rev).collect::<Vec<_>>();
assert_eq!(numbers, vec![4, 3, 2, 1, 0]);

When the condition is false, the function is ignored:

use iter_fi::IterFi;

let numbers = (0..5).iter_if(false, Iterator::rev).collect::<Vec<_>>();
assert_eq!(numbers, vec![0, 1, 2, 3, 4]);
Source

fn map_if<C, T>(self, condition: bool, func: C) -> IterIf<Map<Self, C>, Self>
where Self: Sized, C: Fn(Self::Item) -> T,

If condition is true, apply func to elements in self. Otherwise, skip this call and return self.

This is a shorthand for iter_if(condition, |i| i.map(func)). See the documentation for iter_if for more.

§Examples

When the condition is true, the map is applied:

use iter_fi::IterFi;

let numbers = (0..5).map_if(true, |n| n * 2).collect::<Vec<_>>();
assert_eq!(numbers, vec![0, 2, 4, 6, 8]);

When the condition is false, the map is ignored:

use iter_fi::IterFi;

let numbers = (0..5).map_if(false, |n| n * 2).collect::<Vec<_>>();
assert_eq!(numbers, vec![0, 1, 2, 3, 4]);

Implementors§

Source§

impl<I: Iterator> IterFi for I