1use matchete::{Matcher, Custom};
2
3struct SimpleLevenshteinMetric;
5
6impl SimpleLevenshteinMetric {
7 fn levenshtein_distance(a: &str, b: &str) -> usize {
8 let len_a = a.len();
9 let len_b = b.len();
10
11 if len_a == 0 { return len_b; }
12 if len_b == 0 { return len_a; }
13
14 let mut matrix = vec![vec![0; len_b + 1]; len_a + 1];
15
16 for i in 0..=len_a { matrix[i][0] = i; }
17 for j in 0..=len_b { matrix[0][j] = j; }
18
19 for i in 1..=len_a {
20 for j in 1..=len_b {
21 let cost = if a.chars().nth(i - 1) == b.chars().nth(j - 1) { 0 } else { 1 };
22 matrix[i][j] = (matrix[i - 1][j] + 1)
23 .min(matrix[i][j - 1] + 1)
24 .min(matrix[i - 1][j - 1] + cost);
25 }
26 }
27
28 matrix[len_a][len_b]
29 }
30}
31
32fn main() {
33 let levenshtein_metric = Custom::new(|query: &String, candidate: &String| {
35 let distance = SimpleLevenshteinMetric::levenshtein_distance(query, candidate);
36 let max_len = query.len().max(candidate.len());
37 if max_len == 0 { 1.0 } else { 1.0 - (distance as f64 / max_len as f64) }
38 });
39
40 let matcher = Matcher::<String, String>::new()
42 .add(levenshtein_metric, 1.0)
43 .threshold(0.6);
44
45 let query = String::from("hello");
47 let candidates = vec![
48 String::from("hello"),
49 String::from("helo"),
50 String::from("world"),
51 ];
52
53 println!("Basic String Matching Example");
55 println!("============================");
56 if let Some(result) = matcher.best(&query, &candidates) {
57 println!(
58 "Best match found:\n Score: {:.2}\n Candidate: {}\n Exact: {}",
59 result.score, result.candidate, result.exact
60 );
61 } else {
62 println!("No match found above threshold");
63 }
64}