Skip to content

Commit

Permalink
Add append_path
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
nathell committed Jul 6, 2023
1 parent ba8c344 commit fb1332a
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 14 deletions.
4 changes: 4 additions & 0 deletions LEARN.org
Expand Up @@ -76,6 +76,10 @@ I need to meditate on it some more.

* To explore
** Traits
** Lifetimes

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.

** How to test functions that print stuff?

I.e., what is the Rust equivalent of Clojure’s ~with-out-str~?
38 changes: 24 additions & 14 deletions src/main.rs
Expand Up @@ -23,21 +23,31 @@ fn print_tree<T: Display>(t: &Tree<T>) {
print_tree_with_prefix("", "", "", t);
}

fn append_path<'a>(ut: &mut Tree<&'a str>, path: &'a str) {
let mut t = ut;
for node in path.split("/") {
let match_last = match t.children.last() {
None => false,
Some(x) => x.value == node
};

if match_last {
t = t.children.last_mut().expect("should not happen");
} else {
let subtree = Tree { value: node, children: vec![] };
t.children.push(subtree);
t = t.children.last_mut().expect("should not happen");
}
}
}

fn main() {
let t = Tree {
value: "raz",
children: vec![
Tree {value: "dwa", children: vec![
Tree {value: "trzy", children: vec![]},
Tree {value: "cztery", children: vec![]},
]},
Tree {value: "pięć", children: vec![
Tree {value: "sześć", children: vec![
Tree {value: "siedem", children: vec![]},
]},
]},
Tree {value: "osiem", children: vec![]}]
};
let mut t = Tree {value: "raz", children: vec![]};

append_path(&mut t, "dwa/trzy/trzysta");
append_path(&mut t, "dwa/cztery/cztery-i-pół");
append_path(&mut t, "pięć/sześć/siedem");
append_path(&mut t, "osiem");

print_tree(&t);
}
Expand Down

0 comments on commit fb1332a

Please sign in to comment.