Last active
October 11, 2024 17:54
-
-
Save ClarkeRemy/e0cf7d2eefe143b86054f8e39cd813c7 to your computer and use it in GitHub Desktop.
type level cmp
This file contains hidden or 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
| use std::cmp::Ordering; | |
| type U0 = Zero; | |
| type U1 = Succ<Zero>; | |
| type U2 = Succ<U1>; | |
| type U3 = Succ<U2>; | |
| type U4 = Succ<U3>; | |
| type U5 = Succ<U4>; | |
| fn main() { | |
| let u1 : U1 = Succ(Zero); | |
| let u2 : U2 = Succ(Succ(Zero)); | |
| in_bounds::<U3>() | |
| } | |
| struct Zero; | |
| struct Succ<T : Num>(T); | |
| trait Num {} | |
| impl Num for Zero{} | |
| impl<T : Num> Num for Succ<T>{} | |
| // signature | |
| trait Cmp<Rhs> where Self : Num, Rhs : Num { | |
| type Order; | |
| } | |
| // base cases | |
| impl Cmp<Zero> for Zero { | |
| type Order = EQUAL; | |
| } | |
| impl<T : Num> Cmp<Succ<T>> for Zero { | |
| type Order = LESS; | |
| } | |
| impl<T : Num> Cmp<Zero> for Succ<T> { | |
| type Order = GREATER; | |
| } | |
| // recursive case | |
| impl<T: Num, E : Num> Cmp<Succ<T>> for Succ<E> where E : Cmp<T>{ | |
| type Order = <E as Cmp<T>>::Order; | |
| } | |
| struct GREATER; | |
| struct LESS; | |
| struct EQUAL; | |
| // trait OrderingType{} | |
| trait GT {} | |
| impl GT for GREATER {} | |
| trait LT {} | |
| impl LT for LESS {} | |
| trait EQL {} | |
| impl EQL for EQUAL {} | |
| const fn in_bounds<N>()->bool | |
| where | |
| N : Cmp<U2>, | |
| <N as Cmp<U2>>::Order : GT, | |
| N : Cmp<U5>, | |
| <N as Cmp<U5>>::Order : LT, | |
| { | |
| true | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment