Rust的Peano数字

lje*_*drz 4 functional-programming rust peano-numbers

我想在Rust中编写一个简单的Peano数字实现,似乎我设法让基础知识工作:

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)))));
}
Run Code Online (Sandbox Code Playgroud)

然而,当我决定看看其他人是如何实现的时候,我看到没有人决定用a来做enum,而是用structs和PhantomData(例1,例2).

我的实施有问题吗?这是因为Zero并且Succenum变体而不是真正的类型(所以我的实现不是实际的类型算术)?或者,由于如果我扩展我的实施会遇到困难,它是否更适合采用"主流"方式?

编辑:struct可以在这里看到我使用s 实现Peano数字的困难.

sta*_*lue 9

您的Peano数字位于值的级别,在程序运行时用于计算.这对于游戏来说很好但不是很有用,因为二进制数字i32更有效.

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