Skip to content

Commit d495abe

Browse files
committed
Add im: WIP -- I wanted to capture the error
This is very unhelpful: error[E0387]: cannot borrow data mutably in a captured outer variable in an `Fn` closure --> src/main.rs:30:57 | 30 | .for_each(|filename| tally_words(filename, &mut words).unwrap()); | ^^^^^ | help: consider changing this closure to take self by mutable reference --> src/main.rs:30:19 | 30 | .for_each(|filename| tally_words(filename, &mut words).unwrap()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1 parent ea4896d commit d495abe

File tree

3 files changed

+49
-9
lines changed

3 files changed

+49
-9
lines changed

episode/9/rust/pascal/Cargo.lock

Lines changed: 41 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

episode/9/rust/pascal/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,4 @@ authors = ["Matthias Endler <[email protected]>"]
66
[dependencies]
77
rayon = "1.0.2"
88
structopt = "0.2.10"
9+
im = "12.0.0"

episode/9/rust/pascal/src/main.rs

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
extern crate rayon;
22
#[macro_use] extern crate structopt;
3+
extern crate im;
34

45
use rayon::prelude::*;
56
use structopt::StructOpt;
6-
use std::collections::HashMap;
7+
use im::ordmap::OrdMap;
78
use std::fs;
89
use std::path::{PathBuf, Path};
9-
use std::sync::Mutex;
1010

1111
#[derive(StructOpt)]
1212
struct Cli {
@@ -19,17 +19,16 @@ enum Error {
1919
Lock,
2020
}
2121

22-
type Words = Mutex<HashMap<String, u32>>;
22+
type Words = OrdMap<String, u32>;
2323

2424
fn main() -> Result<(), Box<Error>> {
25-
let w = Words::new(HashMap::new());
25+
let mut words = Words::new();
2626
let args = Cli::from_args();
2727

2828
args.files
2929
.par_iter()
30-
.for_each(|filename| tally_words(filename, &w).unwrap());
30+
.for_each(|filename| tally_words(filename, &mut words).unwrap());
3131

32-
let words = w.lock().map_err(|_| Error::Lock)?;
3332
for (word, count) in words.iter() {
3433
if *count > 1 {
3534
println!("{} {}", count, word)
@@ -39,14 +38,13 @@ fn main() -> Result<(), Box<Error>> {
3938
Ok(())
4039
}
4140

42-
fn tally_words(filename: &Path, w: &Words) -> Result<(), Box<Error>> {
41+
fn tally_words(filename: &Path, words: &mut Words) -> Result<(), Box<Error>> {
4342
let contents = fs::read_to_string(filename).expect("Unable to read file");
4443

4544
for s in contents.split_whitespace() {
4645
let key = s.to_lowercase();
4746
{
48-
let mut map = w.lock().map_err(|_| Error::Lock)?;
49-
*map.entry(key).or_insert(0) += 1;
47+
*words.entry(key).or_insert(0) += 1;
5048
}
5149
}
5250
Ok(())

0 commit comments

Comments
 (0)