6 ms·
this is a really elegant way to take parallel arrays and put them into a table: let codes: Vec<HuffmanCode> = data_table.iter() .zip(code_lengths
by bluejekyll 10y ago
this is a really elegant way to take parallel arrays and put them into a table:
let codes: Vec<HuffmanCode> = data_table.iter()
.zip(code_lengths.iter())
.zip(code_table.iter())
.map(|((&value, &length), &code)| {
HuffmanCode {
length: length,
code: code,
value: value,
}
})
.collect();
Nice!
- masklinn 10y agoYeah though there's something a bit sad to the lack of variable-arity zip/map as you'd find in dynamically typed languages e.g. in Clojure: (mapv HuffmanCode. code_lengths code_table data_table) I don't know if even dependent types would allow for that, given the (variable number of) arguments are all different types.
- lmm 10y agoIt's straightforward with dependent types, unless the language treats multiple arguments (or functions of multiple arguments) specially. In my Scala example in the sibling thread the ().zipped is sort-of-language-level, but one could easily implement the same thing using a HList instead of a tuple; turning the function into a function that accepts a HList requires language-level support or a (standardized) macro but it wouldn't in a Haskell-like language where a function of multiple arguments is curried by default.
- lmm 10y agoIt seems like a lot of work? In scala this would just be: val codes = (data_table, code_lengths, code_table).zipped map HuffmanCode
- mtanski 10y agoRust is not Scala
- lmm 10y agoIt's not, but they're both ML-family languages. I had hoped that Rust would be able to offer a similar level of elegance to Scala.
- bluejekyll 10y agoScala and Rust are not trying to solve problems in the same way though. Rust is a zero-overhead language. Scala has never tried to make that claim.
- nercury 10y agoLooking at the example, I can't find a thing in there that is not required (except the obvious `:Vec<_>` type that is not required). We need `.iter` to tell that iterator is imutable (there is mutable version), we need `.collect` to actually run the iteration. I also don't think objects should have default constructor functions. It may be possible to implement `.zipped` on tuples though.
- steveklabnik 10y ago> (except the obvious `:Vec<_>` type that is not required) It is required, otherwise, `collect()` doesn't know what type of collection to collect into. > It may be possible to implement `.zipped` on tuples though. This is impossible without varargs, no?
- pcwalton 10y ago> This is impossible without varargs, no? Nah, you'd just implement it as an impl over and over on tuples of reasonable size (up to 16 or so). It wouldn't be elegant, but it'd work in practice.
- steveklabnik 10y agoOh right, I see now.