7 ms·
Well, the functional crowd won. An example expression from the parent article: let idx = args // iterate over our arguments .iter() // open eac
by Animats 11y ago
Well, the functional crowd won. An example expression from the parent article:
let idx = args
// iterate over our arguments
.iter()
// open each file
.map(|fname| (fname.as_str(), fs::File::open(fname.as_str())))
// check for errors
.map(|(fname, f)| {
f.and_then(|f| Ok((fname, f)))
.expect(&format!("input file {} could not be opened", fname))
})
// make a buffered reader
.map(|(fname, f)| (fname, io::BufReader::new(f)))
// for each file
.flat_map(|(f, file)| {
file
// read the lines
.lines()
// split into words
.flat_map(|line| {
line.unwrap().split_whitespace()
.map(|w| w.to_string()).collect::<Vec<_>>().into_iter()
})
// prune duplicates
.collect::<HashSet<_>>()
.into_iter()
// and emit inverted index entry
.map(move |word| (word, f))
})
.fold(HashMap::new(), |mut idx, (word, f)| {
// absorb all entries into a vector of file names per word
idx.entry(word)
.or_insert(Vec::new())
.push(f);
Is there editor support for indenting this stuff?
- Chris2048 11y ago> // iterate over our arguments > .iter() hmmm. Not far off the old > i++ // add one to i
- tatterdemalion 11y agoThese are quite different. `.iter()` is equivalent to creating the counter and declaring both the increment and conclusion condition, only its guaranteed to correctly access each member of the collection once and to never be broken, and for many collections (e.g. arrays) it is written in a way which allows for powerful optimizations.
- Chris2048 11y agoI mean in terms of comment useful-ness.
- dikaiosune 11y agoRustfmt can clean that up, but I'm on mobile and can't run the examples through to see what it looks like.
- Jonhoo 11y agoIf you compare that to many of the other solutions on Rosetta Code (https://www.rosettacode.org/wiki/Inverted_index https://www.rosettacode.org/wiki/Inverted_index), that's a pretty neat solution! And yes, as pointed out below, rustfmt would clean this up (mostly by increasing the indentation). I reduced indent to double spaces to make the code denser for the post.
- pcwalton 11y agoI wouldn't say "the functional crowd won"—that's certainly not how I would write the code, and it's not the style that high-profile projects like Servo typically use. Rather, the author clearly prefers functional style, and Rust (like most modern languages) allows you to write in that style if you wish.
- Jonhoo 11y agoOf course. This example was given to show expressiveness. For production-level code, you would break it up more so pieces can be tested individually (as pointed out in another comment).
- devin_lane 11y agoI dunno, I wouldn't say this is as readable as the author mentions. To me, all of the chaining, syntax for closures, and Rust concepts like "into_iter" work to hide the actual algorithm, which is pretty simple. And forget testing, since this is all actually ONE top level call. I certainly wouldn't want to maintain code written like this in any language (and yeah, while you could make pretty much the above in C++ if you really wanted, I wouldn't write it that way.)
- bigger_cheese 11y agoThe syntax doesn't look all that friendly. Even with comments on every second line of the rust code I struggled to work our what it was doing. I opened the external example he linked which has solutions in a number of languages. (https://www.rosettacode.org/wiki/Inverted_index https://www.rosettacode.org/wiki/Inverted_index) I could understand the C version of the code pretty well at a glance. Granted it was long but it looks like the intuitive way I'd write the code. I acknowledge my bias here. I looked at some other languages on the site and both the the C# example and D example look much more readable then the rust code (and I've not used either of those languages either I think they are intended for "system" programming as well) the code as provided in those languages seemed more intuitive.
- Jonhoo 11y agoTo some extent, I think this comes down to familiarity with the functional approach to solving these kinds of problems. Certainly, before I started writing code in Rust, I also preferred the imperative approach you would take in C and Go. Over time though, I've found that I increasingly prefer this way of expressing chained computation. That said, there's certainly a point to be made (and indeed other commenters have made it already) that this isn't code you would want to maintain. For production-level code, it'd be broken down more, so that individual pieces could be reviewed and tested in isolation. The code example here was to demonstrate the expressivity of the language more so than the One True Way of doing it.
- danieldk 11y agoOver time though, I've found that I increasingly prefer this way of expressing chained computation. This looks like code from the 'I found out about FP, let's apply it everywhere'-stage. For instance, if the iteration over arguments was done with a regular for...in loop, the filename would be visible in its scope and the rest of the code could be simplified due to not having to pass the filename everywhere. Also, I don't think this demonstrates expressivity well, because the purported functional construct uses unwrap/expect (it panics). The expressivity of Rust allows you to have the whole expression to have Result has its type fairly easily. (Sorry for ranting a bit, but I think that Not only is this very readable, will tick off people. Which is sad, because it could be changed into something which is more readable but still expressive.)
- lifthrasiir 11y agoMore readable, and IMHO more idiomatic version: (Disclaimer: never tested) let mut idx = HashMap::new(); for fname in &args { let f = match fs::File::open(fname) { Ok(f) => f, Err(e) => panic!("input file {} could not be opened: {}", fname, e), }; let f = io::BufReader::new(f); let mut words = HashSet::new(); for line in f.lines() { for w in line.unwrap().split_whitespace() { if words.insert(w.to_string()) { // new word seen idx.entry(w.to_string()).or_insert(Vec::new()).push(fname); } } } } People who was introduced to the functional approach for the first time seems to enjoy it so much that everything becomes a hard-to-read mess of functions. I had similar experiences with Python list comprehension and C# LINQ.
- bjz_ 11y agoThat one looks to be more efficient too - all those `collect`s in the original are a tad concerning...
- Animats 11y agoDo the "collects" mean that memory is allocated and the whole collection stored temporarily, or is this all iterative generators? (I thought I knew Rust, but I haven't used it for a year, and its usage has changed a lot even if the core language hasn't.)
- steveklabnik 11y agocollect will ... collect it all into some kind of data structure, so yeah, that version would be doing a bunch of allocation.
- ngrilly 11y agoDefinitely more readable to my eyes.
- wott 11y agoYes, it is both much shorter and immediately readable and understandable (without comments!), unlike all the Functional Programming style versions which were proposed in the comments.
- danieldk 11y agoHow I would've written it. Rust beginner, but 'been there, done that' in FP: https://gist.github.com/danieldk/3bd3b84c1a7c8bc8c902314a488cd210 https://gist.github.com/danieldk/3bd3b84c1a7c8bc8c902314a488... (Compiles and seems to work properly on a small document collection.)
- T-R 11y agoPlease, please, please don't associate inlining everything with functional programming. Lambda-lift and name those functions. If you name them, you can ditch most of those comments, too (by moving that information into the names). Not too familiar with Rust syntax, but (to rewrite without changing semantics) something like: let open_file = |fname| (fname.as_str(), fs::File::open(fname.as_str()) ); let check_err = |(fname, f)| { f.and_then(|f| Ok((fname, f))) .expect(&format!("input file {} could not be opened", fname)) }; let to_buff_reader = |(fname, f)| (fname, io::BufReader::new(f)); let line_to_words = |line| { line.unwrap() .split_whitespace() .map(|w| w.to_string()) .collect::<Vec<_>>().into_iter() }; let get_file_words = |(f, file)| { file.lines() .flat_map(line_to_words) .collect::<HashSet<_>>().into_iter() // prune duplicates .map(move |word| (word, f)) }; // emit inverted index entry let add_to_index = |mut idx, (word, f)| { idx.entry(word).or_insert(Vec::new()).push(f); idx }; let idx = args.iter() .map( compose(to_buff_reader, check_err, open_file) ) //[1] .flat_map(get_file_words) .fold(HashMap::new(), add_to_index); [1] Does Rust have a compose function? I hope so. If not, you may need 3 successive "map"s. And stream fusion.
- lifthrasiir 11y ago> Does Rust have a compose function? I hope so. Rust itself does not have a compose function. But a closure works fine, so `|fname| to_buff_reader(check_err(open_file(fname)))` would work. If you want to go further, a nightly Rust allows for this kind of construction: #![feature(unboxed_closures, fn_traits)] // that's why we cannot use stable (yet) struct Composed<F, G>(pub F, pub G); impl<F, G, T, U, V> FnOnce<T> for Composed<F, G> where F: FnOnce<T, Output=U>, G: FnOnce<(U,), Output=V> { type Output = V; extern "rust-call" fn call_once(self, args: T) -> V { self.1(self.0.call_once(args)) } } impl<F, G, T, U, V> FnMut<T> for Composed<F, G> where F: FnMut<T, Output=U>, G: FnMut<(U,), Output=V> { extern "rust-call" fn call_mut(&mut self, args: T) -> V { self.1(self.0.call_mut(args)) } } impl<F, G, T, U, V> Fn<T> for Composed<F, G> where F: Fn<T, Output=U>, G: Fn<(U,), Output=V> { extern "rust-call" fn call(&self, args: T) -> V { self.1(self.0.call(args)) } } fn main() { println!("{}", Composed(|x| x+3, |y| y*4)(5)); // 32 }
- conradev 11y agoRustfmt generally handles this well, yes.