Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust map with predicate

In Rust, is there are map-like equivalent that stops iterating based on a condition I can choose?

I want to iterate over a vector, calling a function on each element as I do so and storing the results, but stop iterating if the function return value ever satisfies a condition

Iterative pseudo-code example:

results = []
for elem in vec:
    result = foo(elem)
    if result is None
        break
    results.push(result)

I can achieve a clumsy equivalent of this with scan by mutating the initial state but (AFAIK) it will still iterate over every element:

Rust-like pseudo-code for scan variant:

results = vec.iter().scan(false, |fail, elem|
    if *fail
        return None

    result = foo(elem)
    if result is None
        *fail = true
    return result
).collect()
like image 752
Iskar Jarak Avatar asked Nov 22 '14 00:11

Iskar Jarak


People also ask

What does .collect do in Rust?

collect() can take all the values in an Iterator 's stream and stick them into a Vec . And the map method is now generating Result<i32, &str> values, so everything lines up.

Are Rust maps randomly generated?

Maps are usually random through procedural generation, but there are also official pre-made maps (Hapis and Savas) and custom community maps through modding.

How do you show the map in Rust?

Press G to open up your current map once you're in a game. You can see the different biomes, roads, rivers, lakes, and Monuments. Every map is an island, and you will always spawn on the beach.

How big can a Rust map be?

I highly recommend you choose a map between 3500 and 4000. Anything above 4000 will result in a warning shown to your players by Rust that they may not be able to play your server without performance issues. Note: The map you choose is what your players will be playing on for the duration of your wipe cycle.


1 Answers

results = vec.iter().map(foo).take_while(|e| e.is_some()).collect()

Iterators in Rust are lazily evaluated. In essence, the call to collect forces each element of the iterator to be evaluated one at a time. This means that as soon as some element fails the predicate in take_while, no further elements will be read from the initial iterator, let alone passed through map.

like image 81
DK. Avatar answered Nov 15 '22 07:11

DK.