Created
June 22, 2025 19:49
-
-
Save jorenham/14b83d35683715e699376177537f2f1a to your computer and use it in GitHub Desktop.
Rust Higher Kinded Types (HKT) practical example
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
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:?}"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
see https://hugopeters.me/posts/14/ for more examples