Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/dtolnay/reduce

iter.reduce(fn) in Rust
https://github.com/dtolnay/reduce

iterator rust

Last synced: about 12 hours ago
JSON representation

iter.reduce(fn) in Rust

Awesome Lists containing this project

README

        

iter.reduce(fn)
===============

[github](https://github.com/dtolnay/reduce)
[crates.io](https://crates.io/crates/reduce)
[docs.rs](https://docs.rs/reduce)
[build status](https://github.com/dtolnay/reduce/actions?query=branch%3Amaster)

This crate gives Iterators a `reduce` function that is similar to
[`fold`][std-fold] but without an initial value. The function returns `None` if
the iterator is empty and `Some(value)` otherwise. This matches the distinction
between [`reduce`][scala-reduce] and [`fold`][scala-fold] in Scala.

[std-fold]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.fold
[scala-reduce]: https://www.scala-lang.org/api/current/scala/collection/Iterator.html#reduce[A1%3E:A](op:(A1,A1)=%3EA1):A1
[scala-fold]: https://www.scala-lang.org/api/current/scala/collection/Iterator.html#fold[A1%3E:A](z:A1)(op:(A1,A1)=%3EA1):A1

```toml
[dependencies]
reduce = "0.1"
```

## Examples

```rust
use reduce::Reduce;

fn main() {
// Reduce a non-empty iterator into Some(value)
let v = vec![1usize, 2, 3, 4, 5];
let sum = v.into_iter().reduce(|a, b| a + b);
assert_eq!(Some(15), sum);

// Reduce an empty iterator into None
let v = Vec::::new();
let sum = v.into_iter().reduce(|a, b| a + b);
assert_eq!(None, sum);
}
```


#### License


Licensed under either of Apache License, Version
2.0
or MIT license at your option.



Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in this crate by you, as defined in the Apache-2.0 license, shall
be dual licensed as above, without any additional terms or conditions.