Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created August 26, 2019 18:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rust-play/2930f45dda6d3b794d62e3b3586eda43 to your computer and use it in GitHub Desktop.
Save rust-play/2930f45dda6d3b794d62e3b3586eda43 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
pub trait HKT<'r, B> {
type A; // Current type
type MA; // Type A swapped with B
type MB; // Current Container type
}
#[macro_export]
macro_rules! derive_hkt {
($t:ident) => {
impl<'r, B: 'r, C> HKT<'r, C> for $t<B> {
type A = B;
type MA = $t<&'r B>;
type MB = $t<C>;
}
};
}
derive_hkt!(Vec);
pub trait Functor<'r, B>: HKT<'r, B> {
fn fmap<F>(self: &'r Self, f: F) -> Self::MB where F: Fn(&Self::A) -> B;
}
pub trait Foldable<'r, B>: HKT<'r, B> {
fn filter<F>(self: &'r Self, f: F) -> Self::MA where F: Fn(&Self::A) -> bool;
}
impl<'r, A: 'r, B> Functor<'r, B> for Vec<A> {
fn fmap<F>(self: &'r Self, f: F) -> Vec<B> where F: Fn(&A) -> B {
let mut result = Vec::with_capacity(self.len());
for val in self {
result.push(f(val));
}
result
}
}
impl <'r, A: 'r, B> Foldable<'r, B> for Vec<A> {
fn filter<F>(self: &'r Self, f: F) -> Self::MA where F: Fn(&Self::A) -> bool {
self.into_iter().filter(|&a| f(a)).collect()
}
}
fn main() {
println!("hello world");
let v: Vec<i32> = vec![1,2,3,4,5,6,7,8];
let v2: Vec<i32> = v.fmap(|&x| x * 3);
let x = v2.filter(|&a| a%2==0);
println!("{:?}", x);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment