Last active
October 29, 2016 17:50
-
-
Save wdv4758h/d2f9c529fc2b2df5ec1b3845b87683ad to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[derive(Debug, PartialEq)] | |
pub enum SimliarityError { | |
DifferentLength | |
} | |
pub type HammingResult = Result<usize, SimliarityError>; | |
/// trait for Hamming Distance | |
pub trait Hamming { | |
fn hamming(&self, rhs: &Self) -> HammingResult; | |
} | |
/// general version of Hamming Distance without checking the length | |
pub fn general_hamming_unsafe<T, I>(a: T, b: T) -> HammingResult | |
where T: Iterator<Item=I>, I: PartialEq { | |
Ok( | |
a.zip(b) | |
.map(|(i, j)| (i != j) as usize) | |
.sum() | |
) | |
} | |
/// Convinient wrapper for Hamming trait | |
pub fn hamming<'a, T>(a: &'a T, b: &'a T) -> HammingResult | |
where T: Hamming { | |
a.hamming(b) | |
} | |
/// Implement Hamming for &str | |
impl<'a> Hamming for &'a str { | |
fn hamming(&self, rhs: &Self) -> HammingResult { | |
general_hamming_unsafe(self.chars(), rhs.chars()) | |
} | |
} | |
#[cfg(test)] | |
mod tests { | |
use hamming; | |
use general_hamming_unsafe; | |
#[test] | |
fn test_hamming() { | |
assert_eq!(1, hamming(&"test1", &"test2").unwrap()); | |
assert_eq!(1, general_hamming_unsafe("test1".chars(), "test2".chars()).unwrap()); | |
assert_eq!(1, general_hamming_unsafe([1, 2, 3].iter(), [2, 2, 3].iter()).unwrap()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment