#numbers #typenum #implemented #faster #system #programming #type-level

peano

The peano numbers implemented in Rust's type system. Consider using typenum instead for much faster type-level numbers.

3 stable releases

Uses old Rust 2015

1.0.2 Sep 4, 2016
1.0.1 Oct 12, 2015

#2496 in Rust patterns

41 downloads per month

MIT/Apache

16KB
206 lines

crates.io Build Status

Peano

Peano is a library for type-level numbers in Rust. It has been supplanted by typenum, which does the same things (and more) and is much faster.

The advantage of peano is that it is much simpler; the entire library is a single file that is under 400 lines of code, many of which are comments.

So, take a look if you want to explore type-level programming. If you want to import a library, use typenum.


lib.rs:

Peano numbers allow us to do arithmetic at compile time using Rust's type system.

The basic idea of the peano numbers is that we first define the number Zero. Then, we inductively define the rest of the natural numbers. For any non-negative natural number N, define its successor, Succ<N>, a positive number. We can now count!

Because we want all the integers and not just the natural numbers, we have to be a little bit careful with these definitions, which is why it is specified that N above must not be negative. Otherwise, when we define predecessors we could end up with Pred<Succ<Zero>> which should represent the number Zero but is a distinct type and would not be treated as such by the compiler.

We can now define negative numbers: For any non-positive natural number N, define its predecessor, Pred<N>, a negative number.

By the definitions of Pred and Succ, we disallow them to be used together.

Conceptually, we now have access to all integers. In practice, we have access to the numbers from -63 to 63 unless we use the #![recursion_limit="N"] lint to increase the allowed number of embedded traits.

In addition to the traits created here, the traits Add, Sub, Mul, Div, and Neg are all implemented for Peano numbers. Note that these traits are used here very differently than is typical. The functions that come with them are not used at all (and will throw an error if you try). Instead, we are using them as operators on types, with the associated type acting as the result of the computation.

Example

use peano::{P2, P3, P4, ToInt};
// 2 + 3 == 5
assert_eq!( 5, <<P2 as Add<P3>>::Output as ToInt>::to_int() );

// 4 / 2 == 2
assert_eq!( 2, <<P4 as Div<P2>>::Output as ToInt>::to_int() );

Note that the ToInt trait here is only used to get an integer output; it is the only runtime operation defined for Peano numbers, and exists primarily for debugging purposes. What is important and generally used is the associated type Output.

Note: Arithmetic with these numbers is very slow unless the numbers are very small. It is strongly recommended that you use the typenum crate instead.

No runtime deps