You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I want a way to easily create a finite iterator from an initial state and a function creating the next state, but, unlike the present function iterate, it takes a function which gives the new state already wrapped in Option, which allows the function to end the iterator. The result of iterate will never end.
I use this implementation based on iterate, and I could commit it to this repository, but I would like to discuss how it should be named and if it could be done better.
pubfniterate_f<St,F>(initial_state:Option<St>,f:F) -> Iterate<St,F>whereF:FnMut(&St) -> Option<St>,{IterateF{state: initial_state,
f }}#[derive(Clone)]#[must_use = "iterators are lazy and do nothing unless consumed"]pubstructIterateF<St,F>{state:Option<St>,f:F}impl<St,F>IteratorforIterateF<St,F>whereF:FnMut(&St) -> Option<St>,{typeItem = St;#[inline]fnnext(&mutself) -> Option<Self::Item>{let next_state = match&self.state{Some(x) => (self.f)(x),None => None};replace(&mutself.state, next_state)}}impl<St,F>FusedIteratorforIterateF<St,F>whereF:FnMut(&St) -> Option<St>,{}
The text was updated successfully, but these errors were encountered:
It does almost what I want, but I dislike that it needs an external variable to track the state. I prefer a single expression to create the iterator. If I enclose the variable with the call to from_fn in a scope to have it as a single expression, I get an error that the variable does not live long enough.
I want a way to easily create a finite iterator from an initial state and a function creating the next state, but, unlike the present function
iterate
, it takes a function which gives the new state already wrapped inOption
, which allows the function to end the iterator. The result ofiterate
will never end.I use this implementation based on
iterate
, and I could commit it to this repository, but I would like to discuss how it should be named and if it could be done better.The text was updated successfully, but these errors were encountered: