Last active
July 12, 2023 16:49
-
-
Save NotBad4U/00c1c7c7135d7067d28adb772d054720 to your computer and use it in GitHub Desktop.
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 Category<'a> { // A | |
type Y<A: 'a, B: 'a>; // B | |
fn id<A: 'a>() -> Self::Y<A, A>; | |
fn compose<A:'a,B: 'a, C:'a>(f: Self::Y<A, B>, g: Self::Y<B, C>) -> Self::Y<A, C>; | |
} | |
struct WrapperFunc; | |
impl <'a>Category<'a> for WrapperFunc { | |
type Y<A: 'a, B: 'a> = Box<dyn Fn (A) -> B + 'a>; | |
fn id<A: 'a>() -> Self::Y<A, A> { | |
Box::new(move |x| x) | |
} | |
fn compose<A:'a,B: 'a,C:'a>(f: Self::Y<A, B>, g: Self::Y<B, C>) -> Self::Y<A,C> { | |
Box::new(move |x| g(f(x))) | |
} | |
} | |
struct Arrow<U, V>(Box<dyn Fn(U) -> V>); | |
impl <'a, U, V>Category<'a> for Arrow<U,V> { | |
type Y<A: 'a, B: 'a> = Box<dyn Fn (A) -> B + 'a>; | |
fn id<A: 'a>() -> Self::Y<A, A> { | |
Box::new(move |x| x) | |
} | |
fn compose<A:'a,B: 'a,C:'a>(f: Self::Y<A, B>, g: Self::Y<B, C>) -> Self::Y<A,C> { | |
Box::new(move |x| g(f(x))) | |
} | |
} | |
impl <'a, U:'a, V :'a> Arrow<'a, U,V> { | |
fn ar(f: impl Fn(U) -> V + 'static) -> Self { | |
Self(Box::new(f)) | |
} | |
fn combine<G:'a,F:'a>(self, f: Arrow<G,F>) -> Arrow<(U, G), (V, F)> { | |
Arrow::ar(Box::new(move |(u, v)| (self.0(u), f.0(v)))) | |
} | |
} | |
fn main() { | |
let arrow = Arrow::ar(Box::new(|x: i32| x +2)); | |
let arrow2 = Arrow::ar(Box::new(|x: i32| x +2)); | |
let compose_arrow = Arrow::<i32, i32>::compose(arrow.0, arrow2.0); | |
println!("{:?}", compose_arrow(50)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment