From fb1332aa5bd0f695604522492ccd893dac28066a Mon Sep 17 00:00:00 2001 From: Daniel Janus Date: Thu, 6 Jul 2023 17:37:33 +0200 Subject: [PATCH] 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. --- LEARN.org | 4 ++++ src/main.rs | 38 ++++++++++++++++++++++++-------------- 2 files changed, 28 insertions(+), 14 deletions(-) diff --git a/LEARN.org b/LEARN.org index 14f98a9..cf4495c 100644 --- a/LEARN.org +++ b/LEARN.org @@ -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~? diff --git a/src/main.rs b/src/main.rs index 4bddeca..f3d7f79 100644 --- a/src/main.rs +++ b/src/main.rs @@ -23,21 +23,31 @@ fn print_tree(t: &Tree) { 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); }