Skip to content

Instantly share code, notes, and snippets.

@kyleheadley kyleheadley/hkt_tree.rs
Last active Feb 10, 2019

Embed
What would you like to do?
demo a struct that can be used with Rc or Arc pointer types
use std::ops::Deref;
use std::rc::Rc;
use std::sync::Arc;
trait PtrFunc<A> {type Ptr:Sized+Clone+Deref+From<A>;}
struct RcPtr;
impl<A> PtrFunc<A> for RcPtr {type Ptr = Rc<A>;}
struct ArcPtr;
impl<A> PtrFunc<A> for ArcPtr {type Ptr = Arc<A>;}
struct TreeNode<T, P> where
P : PtrFunc<TreeNode<T,P>>,
{
val: T,
right: Option<P::Ptr>,
left: Option<P::Ptr>,
}
type RcTree = TreeNode<i32,RcPtr>;
type ArcTree = TreeNode<i32,ArcPtr>;
fn main() {
let rt: RcTree = TreeNode{
val:2,
right:Some(Rc::new(TreeNode{
val:5,
right:None,
left:None,
})),
left:Some(Rc::new(TreeNode{
val:1,
right:None,
left:None,
})),
};
let at: ArcTree = TreeNode{
val:4,
right:Some(Arc::new(TreeNode{
val:1,
right:None,
left:None,
})),
left:Some(Arc::new(TreeNode{
val:6,
right:None,
left:None,
})),
};
println!("The top values are");
println!("{} and {}", rt.val, at.val);
println!("The right values are");
println!("{} and {}", rt.right.unwrap().val, at.right.unwrap().val);
println!("The left values are");
println!("{} and {}", rt.left.unwrap().val, at.left.unwrap().val);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.