Re:The Next Step for Generics
by qppo on Tuesday June 16, 2020 @04:22PM
(#23543599)
Here's some generic code I wrote in Rust recently. I had two unrelated iterators/collections and I needed to flatten and sort them into a single buffer.
Now you could argue that this is just "generics for collections" but the way those iterator combinators are written make heavy use of generics/traits that aren't immediately applicable for collections. Those same combinator techniques can be applied to a whole host of other abstractions that allow for that kind of user code, but it's only possible if the type system empowers library authors to do it.
[ Parent
| on HN ]
You can actually use the power of generics to get rid of the two inner calls to `into_iter()`:
let mut output: Vec<_> =
foo.stuff.into_iter()
.flat_map(|v| v)
.chain(bar.stuff)
.collect();
Re:The Next Step for Generics
by coolreader18 on Tuesday June 16, 2020 @10:42PM
(#23547132)
I believe you can just use `.flatten()` instead of `.flat_map(|v| v)`:
let mut output: Vec<_> =
foo.stuff.into_iter()
.flatten()
.chain(bar.stuff)
.collect();
I might make it slightly more clear what the intent is by doing this: let mut output: Vec<_> =
Iterator::chain(foo.stuff.into_iter().flatten(), bar.stuff)
.collect();
But still basically the same.
Re:The Next Step for Generics
by politician on Wednesday June 17, 2020 @01:47AM
(#23548214)
Yes, functional programming patterns are nice. It's possible to write that even more concisely in JavaScript.