#Cleaner way to write a loop that checks a condition

7 messages · Page 1 of 1 (latest)

brave quail
#

Is there a cleaner, more "rusty" way to write the loop?

fn foo<T: Eq>(things: Vec<T>, others: Vec<T>, start: usize) -> Result<(), ()> {

    for (i, thing) in things.iter().enumerate() {
        if let Some(true) = others.get(start + i).map(|other| other == thing) {
            continue;
        }
        return Err(());
    }

    Ok(())
}
pallid scroll
#

Not sure if this is more 'Rusty', but another approach:

fn foo<T: Eq>(things: Vec<T>, others: Vec<T>, start: usize) -> Result<(), BoxedError> {
    for (i, thing) in things.iter().enumerate() {
        others.get(start + i).map_or_else(
            || return Err("IDX not found"),
            |other| {
                if other != thing {
                    return Err("Doesn't match");
                } else {
                    Ok(())
                }
            },
        )?;
    }
    Ok(())
}
prime widget
#
if things.iter().enumerate().any(|(i, thing)| {
    others
        .get(start + i)
        .map(|other| other != thing)
        .unwrap_or(true)
}) {
    Err(())
} else {
    Ok(())
}
#

if the error you want to return needs to do something with (i, thing), then you can use .find() instead of .any() and do if let Some((i, thing)) = things.iter()....

#

also if you are just inspecting the contents of the Vec, it would be better to take things: &[T] instead of things: Vec<T> (same for others)

#

which once we start doing stuff with slices we can simplify things a bit further

fn foo<T: Eq>(things: &[T], others: &[T], other_offset: usize) -> Result<(), ()> {
    let others = others.get(other_offset..).ok_or(())?;
    // if `things` is longer it will always return an error
    if things.len() > others.len() {
        return Err(());
    }

    if things.iter().zip(others).any(|(thing, other)| thing != other) {
        Err(())
    } else {
        Ok(())
    }
}
#

it may even make sense to have the user pass in others pre-sliced instead of passing in others and this offset