Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Document implementation for HashMap<String, usize> #2

Closed
dbrgn opened this issue Feb 3, 2016 · 2 comments
Closed

Document implementation for HashMap<String, usize> #2

dbrgn opened this issue Feb 3, 2016 · 2 comments

Comments

@dbrgn
Copy link

dbrgn commented Feb 3, 2016

It would probably be useful to have a default implementation of Document and ProcessedDocument for HashMap<String, usize>.

I did a first attempt, but somehow can't get it to compile:

impl<T> Document for HashMap<T, usize> {
    type Term = T;
}

impl<T> ProcessedDocument for HashMap<String, usize> where T : PartialEq {
    fn term_frequency<K>(&self, term: K) -> usize where K : Borrow<T> {
        &self.get(&term).unwrap_or(0)
    }

    fn max(&self) -> Option<&T> {
        match self.iter().max_by_key(|&(_, v)| v) {
            Some(&(ref k, _)) => Some(k),
            None => None
        }
    }
}

The error message I'm getting:

src/lib.rs:75:6: 75:7 error: the type parameter `T` is not constrained by the impl trait, self type, or predicates [E0207]
src/lib.rs:75 impl<T> ProcessedDocument for HashMap<String, usize> where T : PartialEq {
                   ^
src/lib.rs:75:6: 75:7 help: run `rustc --explain E0207` to see a detailed explanation
error: aborting due to previous error

Any ideas?

@ferristseng
Copy link
Owner

Hey,

Thanks for using my library! The issue is you actually don't need the T type parameter in the declaration of the implementation, since your HashMap isn't using it.

Here is a generic version of what you're trying to do (compiles in rustc 1.8.0-nightly):

use std::collections::HashMap;
use std::cmp::Eq;
use std::hash::Hash;

impl<T> Document for HashMap<T, usize> {
  type Term = T;
}

impl<T> ProcessedDocument for HashMap<T, usize> where T : Hash + Eq {
  fn term_frequency<K>(&self, term: K) -> usize where K : Borrow<T> {
    *self.get(term.borrow()).unwrap_or(&0)
  }

  fn max(&self) -> Option<&T> {
    match self.iter().max_by_key(|&(_, v)| v) {
      Some((ref k, _)) => Some(k),
      None => None
    }
  }
}

@dbrgn
Copy link
Author

dbrgn commented Feb 3, 2016

Ah, thanks for that! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants