Skip to content

Instantly share code, notes, and snippets.

@jorenham
Created June 22, 2025 19:49
Show Gist options
  • Save jorenham/14b83d35683715e699376177537f2f1a to your computer and use it in GitHub Desktop.
Save jorenham/14b83d35683715e699376177537f2f1a to your computer and use it in GitHub Desktop.
Rust Higher Kinded Types (HKT) practical example
trait Family {
type Member<T>;
}
trait Functor<A> {
type Of: Family<Member<A> = Self>;
fn fmap<B>(self, f: impl FnMut(A) -> B) -> <Self::Of as Family>::Member<B>;
}
//
struct VecFamily;
impl Family for VecFamily {
type Member<T> = Vec<T>;
}
//
impl<A> Functor<A> for Vec<A> {
type Of = VecFamily;
fn fmap<B>(self, f: impl FnMut(A) -> B) -> Vec<B> {
self.into_iter().map(f).collect()
}
}
fn main() {
let x = vec![1, 2, 3];
let x = x.fmap(|i| format!("{i}"));
println!("{x:?}");
}
@jorenham
Copy link
Author

see https://hugopeters.me/posts/14/ for more examples

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment