I wanted to try to build the correct implementation of Peano numbers with structs, but it seems my game with generics is still not good enough, and I could use some help. I read documents about generics and some qaru.site/questions/1575614 / ... Questions , but they do not fit my case.
I entered the line Peanoand Zeroand Succtypes:
trait Peano {}
struct Zero;
struct Succ<T: Peano>(T);
And a trait is implemented Peanofor both types to be able to abstract over both:
impl Peano for Zero {}
impl<T> Peano for Succ<T> where T: Peano {}
At first I wanted to implement std::ops::Addfor Peano, but I quickly saw that I was doing something very wrong, so I decided to start with something simpler - an enumeration:
trait Enumerate<T: Peano> {
fn succ(&self) -> Succ<T>;
fn pred(&self) -> Option<T>;
}
impl<T> Enumerate<T> for Zero where T: Peano {
fn succ(&self) -> Succ<T> { Succ(*self) }
fn pred(&self) -> Option<T> { None }
}
impl<T> Enumerate<T> for Succ<T> where T: Peano {
fn succ(&self) -> Succ<T> { Succ(*self) }
fn pred(&self) -> Option<T> { Some(self.0) }
}
? ( , ), mismatched types: Box<Succ<T>> instead of Box<Peano>, , .
:
trait Peano {}
#[derive(Debug, Clone, Copy, PartialEq)]
struct Zero;
#[derive(Debug, Clone, Copy, PartialEq)]
struct Succ<T: Peano>(T);
impl Peano for Zero {}
impl<T> Peano for Succ<T> where T: Peano {}
trait Enumerate<T: Peano> {
fn succ(&self) -> Succ<T>;
fn pred(&self) -> Option<T>;
}
impl<T> Enumerate<T> for Zero where T: Peano {
fn succ(&self) -> Succ<T> { Succ(*self) }
fn pred(&self) -> Option<T> { None }
}
impl<T> Enumerate<T> for Succ<T> where T: Peano {
fn succ(&self) -> Succ<T> { Succ(*self) }
fn pred(&self) -> Option<T> { Some(self.0) }
}