Is this idiomatic? It seems powerfully indecipherable/illegible
Is this idiomatic? It seems powerfully indecipherable/illegible
let sum = vec_of_ints
.iter()
.filter(|x| x > 5)
.map(|x| x.pow(2))
.take(3)
.sum()
That is, iterate my vec, only consider values > 5, square them, take the first 3, them sum them.Consider the imperative code:
let mut sum = 0;
let mut n = 0;
for x in vec_of_ints {
if x > 5 {
sum += x.pow(2);
n += 1;
if n == 3 {
break;
}
}
}
I think the chained combinator approach is much easier to see exactly what's happening (and is often higher performance!) state
.db
.send(Queries::GetTopTenHottestYears)
.from_err()
.and_then(move |res| {
result.push(res.unwrap());
state
.db
.send(Queries::GetTopTenColdestYears)
.from_err()
.and_then(move |res| {
result.push(res.unwrap());
state
.db
.send(Queries::GetTopTenHottestMonths)
.from_err()
.and_then(move |res| {
result.push(res.unwrap());
state
.db
.send(Queries::GetTopTenColdestMonths)
.from_err()
.and_then(move |res| {
result.push(res.unwrap());
fut_ok(result)
})
})
})
})
.and_then(|res| Ok(HttpResponse::Ok().json(res)))
.responder()
https://github.com/actix/examples/blob/master/async_db/src/m...My suspicion is the people do this to avoid "variable does not live long enough" type errors.
Example: https://play.rust-lang.org/?gist=7ea1a39971399d0429f0369cb9e...
Oftentimes the iterator will be faster, though, because the compiler can reason about what you're doing easier with an iterator vs. iterating via manual sequential indexing.
Iterators are a typical example of this.
vec![0, 1, 2, 3].into_iter() .filter(|x| x % 2 == 0) // Keep the evens .map(|y| y + 1 ) // Add 1 to elements .rev(); // Reverse the iterator
Adding intermediates would just add noise for code like this.
int.__add__(a, b)
is less idiomatic than a.add(b)
which removes the global abstract. Though I see it looks less symmetric.I'm not a Rustacean - I only speak to the syntax difference.