Created
October 16, 2015 13:00
-
-
Save anonymous/cb78cfb62d5203c6c65a to your computer and use it in GitHub Desktop.
Shared via Rust Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![feature(optin_builtin_traits)] | |
use std::marker::PhantomData; | |
struct Nil; | |
struct Cons<H, T>(H, T); | |
struct Zero; | |
struct One; | |
trait UInt { | |
fn value() -> u64; | |
} | |
impl UInt for Nil { | |
fn value() -> u64 { 0 } | |
} | |
trait Bits: UInt {} | |
impl Bits for Nil {} | |
impl<T: Bits> Bits for Cons<Zero, T> {} | |
impl<T: Bits> Bits for Cons<One, T> {} | |
impl<T: Bits> UInt for Cons<Zero, T> { | |
fn value() -> u64 { T::value() << 1 } | |
} | |
impl<T: Bits> UInt for Cons<One, T> { | |
fn value() -> u64 { (T::value() << 1) | 1 } | |
} | |
trait Add_<A, B> { type Out; } | |
type Add<A, B> = <() as Add_<A, B>>::Out; | |
impl Add_<Nil, Nil> for () { type Out = Nil; } | |
impl<H, T> Add_<Cons<H, T>, Nil> for () { type Out = Cons<H, T>; } | |
impl<H, T> Add_<Nil, Cons<H, T>> for () { type Out = Cons<H, T>; } | |
impl<T1: Bits, T2: Bits> Add_<Cons<Zero, T1>, Cons<Zero, T2>> for () | |
where (): Add_<T1, T2> | |
{ | |
type Out = Cons<Zero, Add<T1, T2>>; | |
} | |
impl<T1: Bits, T2: Bits> Add_<Cons<Zero, T1>, Cons<One, T2>> for () | |
where (): Add_<T1, T2> | |
{ | |
type Out = Cons<One, Add<T1, T2>>; | |
} | |
impl<T1: Bits, T2: Bits> Add_<Cons<One, T1>, Cons<Zero, T2>> for () | |
where (): Add_<T1, T2> | |
{ | |
type Out = Cons<One, Add<T1, T2>>; | |
} | |
impl<T1: Bits, T2: Bits> Add_<Cons<One, T1>, Cons<One, T2>> for () | |
where (): Add_<T1, T2> + Add_<Cons<One, Nil>, Add<T1, T2>> | |
{ | |
type Out = Cons<Zero, Add<Cons<One, Nil>, Add<T1, T2>>>; | |
} | |
trait Mul_<A, B> { type Out; } | |
type Mul<A, B> = <() as Mul_<A, B>>::Out; | |
fn main() { | |
// LSB ---> MSB | |
type Five = Cons<One, Cons<Zero, Cons<One, Nil>>>; | |
type Three = Cons<One, Cons<One, Nil>>; | |
type Eight = Add<Five, Three>; | |
println!("{}", <Eight as UInt>::value()); | |
//println!("{}", Add::<Five, Three>::value()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment