Skip to content

Commit fb1332a

Browse files
committed
Add append_path
A function that appends new nodes to a tree of string slices. With it, parsing stdin should be straightforward: just call append_path for every line. I've gone through multiple broken revisions and fixed many interesting compilation errors in order to arrive at a working version, which highlights an opportunity for a workflow change, coming soon.
1 parent ba8c344 commit fb1332a

2 files changed

Lines changed: 28 additions & 14 deletions

File tree

‎LEARN.org‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,10 @@ I need to meditate on it some more.
7676

7777
* To explore
7878
** Traits
79+
** Lifetimes
80+
81+
The signature of ~append_path~ turned out to require an explicit lifetime declaration. I’ve read the relevant section of the Book (10.3) but I don’t fully grok it yet.
82+
7983
** How to test functions that print stuff?
8084

8185
I.e., what is the Rust equivalent of Clojure’s ~with-out-str~?

‎src/main.rs‎

Lines changed: 24 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -23,21 +23,31 @@ fn print_tree<T: Display>(t: &Tree<T>) {
2323
print_tree_with_prefix("", "", "", t);
2424
}
2525

26+
fn append_path<'a>(ut: &mut Tree<&'a str>, path: &'a str) {
27+
let mut t = ut;
28+
for node in path.split("/") {
29+
let match_last = match t.children.last() {
30+
None => false,
31+
Some(x) => x.value == node
32+
};
33+
34+
if match_last {
35+
t = t.children.last_mut().expect("should not happen");
36+
} else {
37+
let subtree = Tree { value: node, children: vec![] };
38+
t.children.push(subtree);
39+
t = t.children.last_mut().expect("should not happen");
40+
}
41+
}
42+
}
43+
2644
fn main() {
27-
let t = Tree {
28-
value: "raz",
29-
children: vec![
30-
Tree {value: "dwa", children: vec![
31-
Tree {value: "trzy", children: vec![]},
32-
Tree {value: "cztery", children: vec![]},
33-
]},
34-
Tree {value: "pięć", children: vec![
35-
Tree {value: "sześć", children: vec![
36-
Tree {value: "siedem", children: vec![]},
37-
]},
38-
]},
39-
Tree {value: "osiem", children: vec![]}]
40-
};
45+
let mut t = Tree {value: "raz", children: vec![]};
46+
47+
append_path(&mut t, "dwa/trzy/trzysta");
48+
append_path(&mut t, "dwa/cztery/cztery-i-pół");
49+
append_path(&mut t, "pięć/sześć/siedem");
50+
append_path(&mut t, "osiem");
4151

4252
print_tree(&t);
4353
}

0 commit comments

Comments
 (0)