我想尝试使用struct
来构建适当的Peano数字实现,但似乎我的泛型游戏还不够好,我可以使用一些帮助。我阅读泛型文档和someStackOverflowquestions,但它们不适合我的情况。枚举通用结构
我介绍了一个Peano
特质和Zero
和Succ
类型:
trait Peano {}
struct Zero;
struct Succ<T: Peano>(T);
并实施了Peano
性状两种类型能够抽象通过两个:
impl Peano for Zero {}
impl<T> Peano for Succ<T> where T: Peano {}
起初我想为Peano
实现std::ops::Add
,但我很快发现我做的事情非常错误,所以我决定从简单的事情开始 - 枚举:
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) } // mismatched types: Zero instead of T
fn pred(&self) -> Option<T> { None }
}
impl<T> Enumerate<T> for Succ<T> where T: Peano {
fn succ(&self) -> Succ<T> { Succ(*self) } // mismatched types: Succ<T> instead of T
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) }
}
工作就像一个魅力,谢谢! – ljedrz
并且感谢关于类型级计算的额外信息 - 我的特质-foo已经提高了很多。 – ljedrz
@ljedrz:我会注意到,如果你想深入到类型级计算中,你可能会对[typenum](https://crates.io/crates/typenum)箱子感兴趣。 –