4

I wanted to write a simple implementation of Peano numbers in Rust and it seems that I managed to get the basics working:

use self::Peano::*;
use std::ops::Add;

#[derive(Debug, PartialEq)]
enum Peano {
    Zero,
    Succ(Box<Peano>)
}

impl Add for Peano {
    type Output = Peano;

    fn add(self, other: Peano) -> Peano {
        match other {
            Zero => self,
            Succ(x) => Succ(Box::new(self + *x))
        }
    }
}

fn main() {
    assert_eq!(Zero + Zero, Zero);
    assert_eq!(Succ(Box::new(Zero)) + Zero, Succ(Box::new(Zero)));
    assert_eq!(Zero + Succ(Box::new(Zero)), Succ(Box::new(Zero)));
    assert_eq!(Succ(Box::new(Zero)) + Succ(Box::new(Zero)), Succ(Box::new(Succ(Box::new(Zero)))));
    assert_eq!(Succ(Box::new(Zero)) + Zero + Succ(Box::new(Zero)), Succ(Box::new(Succ(Box::new(Zero)))));
}

However, when I decided to take look at how it was implemented by others, I saw that noone decided to do it with an enum, but rather with structs and PhantomData (example 1, example 2).

Is there something wrong with my implementation? Is this because Zero and Succ are enum variants and not true types (so my implementation is not actual type arithmetic)? Or is it just preferable to do this the "mainstream" way due to difficulties that would occur if I expanded my implementation?

Edit: my struggles with implementing Peano numbers using structs can be seen here.

4

1 回答 1

9

您的 Peano 数字处于值的级别,在程序运行时用于计算。这很适合玩,但不是很有用,因为像二进制数这样i32的效率更高。

其他实现表示类型级别的 Peano 数字,您目前不能使用普通数字。这允许表达依赖于数字的类型,例如固定大小的数组。然后在编译器推断类型时进行计算。

于 2016-09-03T18:48:09.703 回答