### 3 stable releases

Uses old Rust 2015

1.0.2 | Sep 4, 2016 |
---|---|

1.0.1 | Oct 12, 2015 |

#**953** in Rust patterns

**MIT/Apache**

16KB

206 lines

# 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

. Then, we
inductively define the rest of the natural numbers. For any non-negative natural number
`Zero`

, define its successor, `N`

, a positive number. We can now count!`Succ <N>`

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

above
must not be negative. Otherwise, when we define predecessors we could end up with
`N`

which should represent the number `Pred <Succ<Zero>>`

`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

, define
its predecessor, `N`

, a negative number.`Pred <N>`

By the definitions of

and `Pred`

, we disallow them to be used together.`Succ`

Conceptually, we now have access to all integers. In practice, we have access to
the numbers from -63 to 63 unless we use the

lint to increase
the allowed number of embedded traits.`#!``[``recursion_limit``=``"`N`"``]`

In addition to the traits created here, the traits

, `Add`

, `Sub`

, `Mul`

, and `Div`

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 `Neg`*types*,
with the associated type acting as the result of the computation.

# Example

`use` `peano``::``{``P2``,` `P3``,` `P4``,` ToInt`}``;`
`#` `use` `std``::``ops``::``{`Add`,` Div`}``;`
`//` 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

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 `ToInt`

.`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.