Peano numbers in Rust

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

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 see how it was implemented by others, I saw that no one decided to do this with enum, but rather with structand PhantomData( example 1 , example 2 ).

Is there something wrong with my implementation? This is because, Zeroand Succare enumoptions, not true types (so my implementation is not an actual arithmetic type)? Or is it simply preferable to do this the “main” way because of the difficulties that may arise if I expand my implementation?

: Peano struct .

+4
1

Peano , . , , , i32, .

, . , , . , .

+9

Source: https://habr.com/ru/post/1653534/


All Articles