4 ms·
Let’s say I have a closure `fn() -> Option<T>`—how do I turn that into an Iterator? Maybe it’s possible with the stdlib and I’m just not familiar? EDIT: I thin
by throwaway894345 6y ago
Let’s say I have a closure `fn() -> Option<T>`—how do I turn that into an Iterator? Maybe it’s possible with the stdlib and I’m just not familiar?
EDIT: I think this is it: https://news.ycombinator.com/item?id=27050861 https://news.ycombinator.com/item?id=27050861
- kzrdude 6y agoLet's say std::iter::from_fn didn't exist. Then you'd need to make something that ends the iterator when the function returns none, you could do it like this: std::iter::repeat_with(f).take_while(|elt| elt.is_some()).filter_map(|elt| elt) Where `.filter_map()` removes the Option layer and `repeat_with` creates an initially infinite iterator from your function `f`. Long time ago, `repeat_with` might not have existed. Maybe you'd do something like this instead for that in Rust 1.0.0: `std::iter::repeat(()).map(|_| f())...` You prefer to use std::iter::from_fn now that it exists, of course! To be honest, making a simple iterator adaptor is quite easy too, so you could have a knack at making one you are missing - if you can't find it in std or in the crate itertools already.