rust_fp_categories/
pure.rs1use std::rc::Rc;
2
3pub trait Pure {
4 type Elm;
5 type M<U>;
6
7 fn pure(value: Self::Elm) -> Self::M<Self::Elm>;
8
9 fn unit() -> Self::M<()>;
10}
11
12macro_rules! pure_numeric_impl {
13 ($($t:ty)*) => ($(
14 impl Pure for $t {
15 type Elm = $t;
16 type M<U> = U;
17
18 fn pure(value: Self::Elm) -> Self::M<Self::Elm> {
19 value
20 }
21
22 fn unit() -> Self::M<()> {
23 ()
24 }
25 }
26 )*)
27}
28
29pure_numeric_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
30
31impl<A> Pure for Rc<A> {
32 type Elm = A;
33 type M<U> = Rc<U>;
34
35 fn pure(value: Self::Elm) -> Self::M<Self::Elm> {
36 Rc::new(value)
37 }
38
39 fn unit() -> Self::M<()> {
40 Rc::new(())
41 }
42}
43
44impl<A> Pure for Box<A> {
45 type Elm = A;
46 type M<U> = Box<U>;
47
48 fn pure(value: Self::Elm) -> Self::M<Self::Elm> {
49 Box::new(value)
50 }
51
52 fn unit() -> Self::M<()> {
53 Box::new(())
54 }
55}
56
57impl<A> Pure for Option<A> {
58 type Elm = A;
59 type M<U> = Option<U>;
60
61 fn pure(value: Self::Elm) -> Self::M<Self::Elm> {
62 Some(value)
63 }
64
65 fn unit() -> Self::M<()> {
66 Some(())
67 }
68}
69
70impl<A, E> Pure for Result<A, E> {
71 type Elm = A;
72 type M<U> = Result<U, E>;
73
74 fn pure(value: Self::Elm) -> Self::M<Self::Elm> {
75 Ok(value)
76 }
77
78 fn unit() -> Self::M<()> {
79 Ok(())
80 }
81}
82
83impl<A> Pure for Vec<A> {
84 type Elm = A;
85 type M<U> = Vec<U>;
86
87 fn pure(value: Self::Elm) -> Self::M<Self::Elm> {
88 vec![value]
89 }
90
91 fn unit() -> Self::M<()> {
92 vec![()]
93 }
94}