Crate balanced_ternary

Source
Expand description

A balanced ternary data structure.

A Ternary object in this module represents a number in the balanced ternary numeral system. Balanced ternary is a non-standard positional numeral system that uses three digits: {-1, 0, +1} represented here as Neg for -1, Zero for 0, and Pos for +1. It is useful in some domains of computer science and mathematics due to its arithmetic properties and representation symmetry.

§Data Structures

  • Digit Enum: Represents a single digit for balanced ternary values, with possible values:

    • Neg for -1
    • Zero for 0
    • Pos for +1
  • Ternary Struct: Represents a balanced ternary number as a collection of Digits. Provides utility functions for conversion, parsing, and manipulation.

§Examples

§Converting between representations:

use balanced_ternary::*;

let ternary = Ternary::from_dec(5);
assert_eq!(ternary.to_string(), "+--");
assert_eq!(ternary.to_dec(), 5);

let parsed = Ternary::parse("+--");
assert_eq!(parsed.to_string(), "+--");
assert_eq!(parsed.to_dec(), 5);

§Negative numbers:

use balanced_ternary::*;

let neg_five = Ternary::from_dec(-5);
assert_eq!(neg_five.to_string(), "-++");
assert_eq!(neg_five.to_dec(), -5);

let negated = -&neg_five;
assert_eq!(negated.to_string(), "+--");
assert_eq!(negated.to_dec(), 5);

§Larger numbers:

use balanced_ternary::*;

let big = Ternary::from_dec(121);
assert_eq!(big.to_string(), "+++++");
assert_eq!(big.to_dec(), 121);

let neg_big = Ternary::from_dec(-121);
assert_eq!(neg_big.to_string(), "-----");
assert_eq!(neg_big.to_dec(), -121);

§Operations

use balanced_ternary::Ternary;

let repr9 = Ternary::parse("+00");
let repr4 = Ternary::parse("++");
let repr13 = &repr9 + &repr4;
let repr17 = &repr13 + &repr4;
let repr34 = &repr17 + &repr17;

assert_eq!(repr13.to_string(), "+++");
assert_eq!(repr17.to_string(), "+-0-");
assert_eq!(repr34.to_string(), "++-+");

let repr30 = &repr34 - &repr4;
assert_eq!(repr30.to_dec(), 30);
assert_eq!(repr30.to_string(), "+0+0");

Re-exports§

pub use crate::digit::Digit;
pub use crate::digit::Digit::Neg;
pub use crate::digit::Digit::Pos;
pub use crate::digit::Digit::Zero;
pub use crate::tryte::Tryte;

Modules§

digit
Module: Balanced Ternary Digit
operations
This module provides implementations for arithmetic operations on the Ternary type such as addition, subtraction, multiplication, and division. Using Ternary arithmetic:
tryte
A module defining the Tryte structure and its associated functionality.

Structs§

Ternary
Represents a balanced ternary number using a sequence of Digits.