Advertisement
Guest User

Untitled

a guest
Oct 15th, 2019
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. use std::fmt;
  2. use std::sync::Arc;
  3.  
  4. fn main() {
  5. let add_c = curry2(add);
  6. let mul_c = curry2(mul);
  7.  
  8. let add_1 = add_c.clone()(1);
  9. let add_5 = add_c.clone()(5);
  10.  
  11. let mul_4 = mul_c.clone()(4);
  12.  
  13. let complex_f = compose(compose(add_1.clone(), mul_4.clone()).clone(), add_5.clone());
  14.  
  15. let m8 = Maybe::Just(8);
  16. let mn = Maybe::Nothing;
  17.  
  18. let fmap_complex_f = fmap(complex_f.clone());
  19.  
  20. println!("The value of add_c(3)(5) is: {}", add_c.clone()(3)(5));
  21. println!("The value of add_1(5) is: {}", add_1.clone()(5));
  22. println!("The value of add_5(7) is: {}", add_5.clone()(7));
  23. println!("The value of complex_f(12) (we are going to have: 57) is: {}", complex_f.clone()(12));
  24. println!("fmap complex_f to m8: {}", fmap_complex_f.clone()(m8));
  25. println!("fmap complex_f to mn: {}", fmap_complex_f.clone()(mn));
  26. }
  27.  
  28. fn add(x: i32, y: i32) -> i32 {
  29. x + y
  30. }
  31.  
  32. fn mul(x: i32, y: i32) -> i32 {
  33. x * y
  34. }
  35.  
  36. fn curry2<T1,T2,T3>(f: fn(T1, T2) -> T3) -> Arc<dyn Fn(T1) -> Arc<dyn Fn(T2) -> T3>> where
  37. T1: 'static + Copy,
  38. T2: 'static + Copy,
  39. T3: 'static + Copy, {
  40. Arc::new(move |x| {
  41. Arc::new(move |y| f(x,y))
  42. })
  43. }
  44.  
  45. // compose :: (a -> b) -> (b -> c) -> (a -> c)
  46. // compose f g = \x -> g(f(x))
  47. fn compose<T1,T2,T3>(f: Arc<dyn Fn(T1) -> T2>, g: Arc<dyn Fn(T2) -> T3>) -> Arc<dyn Fn(T1) -> T3> where
  48. T1: 'static + Copy,
  49. T2: 'static + Copy,
  50. T3: 'static + Copy, {
  51. Arc::new(move |x| g(f(x)))
  52. }
  53.  
  54. enum Maybe<T> where
  55. T: Copy {
  56. Nothing,
  57. Just(T)
  58. }
  59.  
  60. impl<T> fmt::Display for Maybe<T> where
  61. T: Copy + std::fmt::Display {
  62. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  63. match self {
  64. Maybe::Just(x) => {write!(f, "{}", x)}
  65. Maybe::Nothing => {write!(f, "Nothing")}
  66. }
  67. }
  68. }
  69.  
  70. fn fmap<T1, T2>(f: Arc<dyn Fn(T1) -> T2>) -> Arc<dyn Fn(Maybe<T1>) -> Maybe<T2>> where
  71. T1: 'static + Copy,
  72. T2: 'static + Copy, {
  73. Arc::new(move |mx| match mx{
  74. Maybe::Just(x) => { Maybe::Just(f(x)) }
  75. Maybe::Nothing => { Maybe::Nothing }
  76. })
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement