My new favorite way to represent AST's (or any recursive type really) in rust
For a long time i represented my Abstract Syntax Trees like so
pub enum AST{
Application(Box<(AST,AST)>),
Abstraction(Box<(AST,AST)>),
Variable(usize)
}
Recently i discovered another way. Instead of having an enum i could lift AST into a trait and variants to its own structures.
pub struct Application<Fun:AST, Args:Ast>( Fun,Args)
pub struct Abstraction<Body:Ast>( Variable,Body)
pub struct Variable(usize)
pub trait AST {
// ... fill your methods here
}
impl <Fun:AST, Args:Ast> AST for Application<Fun,Args>{}
impl <Body:AST> AST for Abstraction<Body>{}
impl AST for Variable{}
The nice thing here is that we got rid of the pesky \``Box\\ and stronger typing requirements \[look at Abstraction\] (although the last point could've been made with regular enums as well).
Anyways I just wanted to share this