Vec<T>, Fn(&T) -> Option<X>, ==> Option<X>

I have the following:

T, X: Types;
lst: Vec<T>;
f: Fn(&T) -> Option<X>;

Then I have the following:

lst.iter().enumerate().map(|(i, x)| Some((i, f(x)?)))
has type Iterator<Option<(usize, X)>>??

Question: How do I collect this into a Option<usize, X> ? If there are multiple Some, return first; otherwise return None.

Iterator::find

lst.into_iter().find(f)

1 Like

Thanks! I came up with .filter_map().next(), but find is definitely better.

Recently you've asked a lot of questions that can be answered with Iterator methods. Please look through the Iterator docs to see what's available, it is a gold mine of helpful functions.

3 Likes

I wonder if you might be attributing to me questions not asked by me.

I count 3 in the past week and 7 in the past month -- is this considered rude / impolite ?

I don't want to make excuses -- what's currently happening is that IntelliJ/Rust seems to be much faster at type inference of closures, so I'm rewriting lots of for loops in a more functional manner.

The issue I'm running into with the Iterator docs is that (1) I often guess the wrong English word, (2) then I'm linearly scanning through the 60+ function type signatures to see any match.

What would be really useful would be a better way to search fully expanded type signatures (aliases + where clauses get in the way here), i.e. being able to type (not literal regex)

"Fn(.*Option.*) -> Option.*"

and have it narrow down to functions that return an Option, and takes as input a Fn that takes Option as an input.

2 Likes

Ok, I think I am just misremembering how often you've asked questions, sorry.

Ok, that does seem like an issue with the docs.

I would love this, I htink Haskell has this with their docs on Hoogle and this would be great for Rust docs.

To be clear, the "3 in last week, 7 in last month" is only referring to questions answerable via Iterator docs.

But I think this is meta now. Thanks again for the response. I'll try to check the Iterator docs more and cut down on Iterator questions.

1 Like