Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::fmt;
- use std::sync::Arc;
- fn main() {
- let add_c = curry2(add);
- let mul_c = curry2(mul);
- let add_1 = add_c.clone()(1);
- let add_5 = add_c.clone()(5);
- let mul_4 = mul_c.clone()(4);
- let complex_f = compose(compose(add_1.clone(), mul_4.clone()).clone(), add_5.clone());
- let m8 = Maybe::Just(8);
- let mn = Maybe::Nothing;
- let fmap_complex_f = fmap(complex_f.clone());
- println!("The value of add_c(3)(5) is: {}", add_c.clone()(3)(5));
- println!("The value of add_1(5) is: {}", add_1.clone()(5));
- println!("The value of add_5(7) is: {}", add_5.clone()(7));
- println!("The value of complex_f(12) (we are going to have: 57) is: {}", complex_f.clone()(12));
- println!("fmap complex_f to m8: {}", fmap_complex_f.clone()(m8));
- println!("fmap complex_f to mn: {}", fmap_complex_f.clone()(mn));
- }
- fn add(x: i32, y: i32) -> i32 {
- x + y
- }
- fn mul(x: i32, y: i32) -> i32 {
- x * y
- }
- fn curry2<T1,T2,T3>(f: fn(T1, T2) -> T3) -> Arc<dyn Fn(T1) -> Arc<dyn Fn(T2) -> T3>> where
- T1: 'static + Copy,
- T2: 'static + Copy,
- T3: 'static + Copy, {
- Arc::new(move |x| {
- Arc::new(move |y| f(x,y))
- })
- }
- // compose :: (a -> b) -> (b -> c) -> (a -> c)
- // compose f g = \x -> g(f(x))
- fn compose<T1,T2,T3>(f: Arc<dyn Fn(T1) -> T2>, g: Arc<dyn Fn(T2) -> T3>) -> Arc<dyn Fn(T1) -> T3> where
- T1: 'static + Copy,
- T2: 'static + Copy,
- T3: 'static + Copy, {
- Arc::new(move |x| g(f(x)))
- }
- enum Maybe<T> where
- T: Copy {
- Nothing,
- Just(T)
- }
- impl<T> fmt::Display for Maybe<T> where
- T: Copy + std::fmt::Display {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- match self {
- Maybe::Just(x) => {write!(f, "{}", x)}
- Maybe::Nothing => {write!(f, "Nothing")}
- }
- }
- }
- fn fmap<T1, T2>(f: Arc<dyn Fn(T1) -> T2>) -> Arc<dyn Fn(Maybe<T1>) -> Maybe<T2>> where
- T1: 'static + Copy,
- T2: 'static + Copy, {
- Arc::new(move |mx| match mx{
- Maybe::Just(x) => { Maybe::Just(f(x)) }
- Maybe::Nothing => { Maybe::Nothing }
- })
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement