【发布时间】:2016-09-16 01:33:12
【问题描述】:
我想尝试使用structs 构建 Peano 数字的正确实现,但我的泛型游戏似乎还不够好,我可以使用一些帮助。我阅读了有关泛型和 some StackOverflow questions 的文档,但它们不适合我的情况。
我引入了Peano 特征和Zero 和Succ 类型:
trait Peano {}
struct Zero;
struct Succ<T: Peano>(T);
并为这两种类型实现了Peano trait,以便能够对两者进行抽象:
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) }
}
【问题讨论】: