Skip to content

Instantly share code, notes, and snippets.

@trvswgnr
Created December 5, 2024 07:43
Show Gist options
  • Save trvswgnr/a42ec99a9cf1cf6d69b11ba5fe2b2683 to your computer and use it in GitHub Desktop.
Save trvswgnr/a42ec99a9cf1cf6d69b11ba5fe2b2683 to your computer and use it in GitHub Desktop.
functor in rust
/*
[dependencies]
*/
mod sealed {
pub trait IsType<T: ?Sized> {}
impl<T: ?Sized> IsType<T> for T {}
}
/// Trait `IsType<T>` is implemented if and only if `Self` is `T`
pub trait IsType<T: ?Sized>: sealed::IsType<T> {
/// Convert from `T` to `Self` (no-op)
fn identity_from(x: T) -> Self
where
Self: Sized,
T: Sized;
/// Convert from `Self` to `T` (no-op)
fn identity_into(self) -> T
where
Self: Sized,
T: Sized;
}
impl<T: ?Sized> IsType<T> for T {
fn identity_from(x: T) -> Self
where
Self: Sized,
T: Sized,
{
x
}
fn identity_into(self) -> T
where
Self: Sized,
T: Sized,
{
self
}
}
pub trait Functor: IsType<Self::F<Self::A>> {
type F<B>: Functor;
type A;
fn fmap<F, B>(self, f: F) -> Self::F<B>
where
F: FnMut(Self::A) -> B;
}
impl<T> Functor for Option<T> {
type F<B> = Option<B>;
type A = T;
fn fmap<F, B>(self, f: F) -> Option<B>
where
F: FnMut(T) -> B,
{
Option::map(self, f)
}
}
fn main() {
println!("");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment