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) 상자에 관심이있을 수 있습니다. –