From c7b95ea0eb4e6c550fbede594ccc2f938331a27f Mon Sep 17 00:00:00 2001 From: TudbuT Date: Wed, 15 Nov 2023 15:41:33 +0100 Subject: [PATCH] Add another example, add call_as! --- Cargo.toml | 2 +- examples/list.rs | 20 ++++++---------- examples/math.rs | 62 ++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 7 ++++++ 4 files changed, 77 insertions(+), 14 deletions(-) create mode 100644 examples/math.rs diff --git a/Cargo.toml b/Cargo.toml index ba65888..ab1c5ce 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "type-fn" -version = "0.1.1" +version = "0.1.2" edition = "2021" description = "Allows for simpler coding of type-level logic, e.g. for type-number systems." license = "MIT" diff --git a/examples/list.rs b/examples/list.rs index 89b34b5..f032597 100644 --- a/examples/list.rs +++ b/examples/list.rs @@ -28,19 +28,13 @@ fn main() { struct World; type MyListA = EmptyList; - type MyListB = as TypeFn>::Ret; - type MyListC = as TypeFn>::Ret; + type MyListB = call!(AddElement); + type MyListC = call!(AddElement); - type RemovalA = as TypeFn>::Ret; - println!( - "{}", - any::type_name::< as TypeFn>::Ret>() - ); + type RemovalA = call!(RemoveLastElement); + println!("{}", any::type_name::)>()); - type MyListD = as TypeFn>::Ret; - type RemovalB = as TypeFn>::Ret; - println!( - "{}", - any::type_name::< as TypeFn>::Ret>() - ); + type MyListD = call!(GetChangedList); + type RemovalB = call!(RemoveLastElement); + println!("{}", any::type_name::)>()); } diff --git a/examples/math.rs b/examples/math.rs new file mode 100644 index 0000000..ca76387 --- /dev/null +++ b/examples/math.rs @@ -0,0 +1,62 @@ +use std::marker::PhantomData; + +use type_fn::*; + +pub struct Zero; +pub struct Succ(PhantomData); +pub trait ToNum { + const RESULT: NumType; +} +impl ToNum for Zero { + const RESULT: usize = 0; +} +impl ToNum for Succ +where + T: ToNum, +{ + const RESULT: usize = T::RESULT + 1; +} +type_fn! { + pub fn Add; + pub fn Sub; + pub fn Mul; + pub fn Pow; + + pub fn Root; + + pub fn DistanceDirect; +} +type_fn_impl! { + fn Add< => Zero, Rhs> => Rhs; + fn Add Succ, Rhs> + where + Add: + TypeFn, + => Succ)>; + + fn Sub Zero> => Lhs; + fn Sub Succ, Rhs => Succ> + where + Sub : + TypeFn, + => call!(Sub); + + fn Mul< => Zero, Rhs> => Zero; + fn Mul Succ, Rhs> + where + Mul: + TypeFn, + Add)>: + TypeFn, + => call!(Add)>); + + fn Pow Zero> => Succ; + fn Pow Succ> + where + Pow: + TypeFn, + Mul)>: + TypeFn, + => call!(Mul)>); +} + +fn main() { + type One = Succ; + type Two = call!(Add); + type Five = call!(Add)>); + println!("2^5: {}", ) as ToNum>::RESULT); +} diff --git a/src/lib.rs b/src/lib.rs index 51c9b47..8ef8bf3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -13,6 +13,13 @@ macro_rules! call { }; } +#[macro_export] +macro_rules! call_as { + ($fty:ty => $($fn:tt)+) => { + <$($fn)+ as $fty>::Ret + }; +} + /// Verifies equality between two types at compile-time. #[macro_export] macro_rules! assert_types_eq {