Skip to content

Instantly share code, notes, and snippets.

@kevinbarabash
Created April 13, 2023 03:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinbarabash/2f42f0ccdd538c70230292303879fce2 to your computer and use it in GitHub Desktop.
Save kevinbarabash/2f42f0ccdd538c70230292303879fce2 to your computer and use it in GitHub Desktop.
fmt::Display implementation for arena based tree struct
use std::fmt;
enum Node<T> {
Add { left: T, right: T },
Mul { left: T, right: T },
Num { value: i64 },
}
struct Arena {
nodes: Vec<Node<usize>>,
}
struct Combo<'a> {
arena: &'a Arena,
node: Node<Box<Self>>,
}
impl<'a> fmt::Display for Combo<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match &self.node {
Node::Add { left, right } => write!(f, "({} + {})", left, right),
Node::Mul { left, right } => write!(f, "({} * {})", left, right),
Node::Num { value } => write!(f, "{}", value),
}
}
}
impl Node<usize> {
fn to_combo<'a>(&self, arena: &'a Arena) -> Combo<'a> {
match self {
Node::Add { left, right } => Combo {
arena,
node: Node::Add {
left: Box::from(arena.nodes[*left].to_combo(arena)),
right: Box::from(arena.nodes[*right].to_combo(arena)),
},
},
Node::Mul { left, right } => Combo {
arena,
node: Node::Mul {
left: Box::from(arena.nodes[*left].to_combo(arena)),
right: Box::from(arena.nodes[*right].to_combo(arena)),
},
},
Node::Num { value } => Combo {
arena,
node: Node::Num { value: *value },
},
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn new_num(arena: &mut Arena, value: i64) -> usize {
let node = Node::Num { value };
let index = arena.nodes.len();
arena.nodes.push(node);
index
}
fn new_add(arena: &mut Arena, left: usize, right: usize) -> usize {
let node = Node::Add { left, right };
let index = arena.nodes.len();
arena.nodes.push(node);
index
}
#[test]
fn test_foo() {
let mut arena = Arena { nodes: vec![] };
let left = new_num(&mut arena, 5);
let right = new_num(&mut arena, 10);
let add = new_add(&mut arena, left, right);
let combo = arena.nodes[add].to_combo(&arena);
eprintln!("combo: {combo}",);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment