rust_lstar/knowledge_base/
base.rs1use super::tree::KnowledgeTree;
2use crate::query::OutputQuery;
3use crate::word::Word;
4
5use super::stats::KnowledgeBaseStats;
6
7pub trait KnowledgeBaseTrait {
9 fn resolve_query(&mut self, query: &mut OutputQuery) -> Result<(), String>;
10 fn add_word(&mut self, input_word: &Word, output_word: &Word) -> Result<(), String>;
11}
12
13pub struct KnowledgeBase {
15 knowledge_tree: KnowledgeTree,
16 stats: KnowledgeBaseStats,
17}
18
19impl KnowledgeBase {
20 pub fn new() -> Self {
21 KnowledgeBase {
22 knowledge_tree: KnowledgeTree::new(),
23 stats: KnowledgeBaseStats::new(),
24 }
25 }
26
27 pub fn resolve_query(&mut self, query: &mut OutputQuery) -> Result<(), String> {
28 let output_word = self.resolve_word(&query.input_word)?;
29 query.output_word = Some(output_word);
30 Ok(())
31 }
32
33 fn resolve_word(&mut self, word: &Word) -> Result<Word, String> {
34 self.stats.increment_nb_query();
35 self.stats.add_nb_letter(word.len());
36
37 match self.knowledge_tree.get_output_word(word) {
38 Ok(output) => Ok(output),
39 Err(_) => {
40 self.stats.increment_nb_submitted_query();
41 self.stats.add_nb_submitted_letter(word.len());
42
43 let output = self.execute_word(word)?;
44 self.knowledge_tree.add_word(word, &output)?;
45 Ok(output)
46 }
47 }
48 }
49
50 fn execute_word(&self, _word: &Word) -> Result<Word, String> {
51 Err("Passive inference process".to_string())
52 }
53
54 pub fn add_word(&mut self, input_word: &Word, output_word: &Word) -> Result<(), String> {
55 self.knowledge_tree.add_word(input_word, output_word)
56 }
57
58 pub fn stats(&self) -> &KnowledgeBaseStats {
59 &self.stats
60 }
61
62 pub fn stats_mut(&mut self) -> &mut KnowledgeBaseStats {
63 &mut self.stats
64 }
65}
66
67impl Default for KnowledgeBase {
68 fn default() -> Self {
69 Self::new()
70 }
71}
72
73impl KnowledgeBaseTrait for KnowledgeBase {
74 fn resolve_query(&mut self, query: &mut OutputQuery) -> Result<(), String> {
75 self.resolve_query(query)
76 }
77
78 fn add_word(&mut self, input_word: &Word, output_word: &Word) -> Result<(), String> {
79 self.add_word(input_word, output_word)
80 }
81}