ty_ops/
maybe.rs

1use std::marker::PhantomData;
2use crate::*;
3use crate::classes::*;
4
5#[derive(Copy, Clone, Default)]
6pub struct Maybe<T: Type>(PhantomData<T>);
7
8impl<T: Type> Type for Maybe<T> {}
9
10#[derive(Copy, Clone, Default)]
11pub struct Nothing<T: Type>(PhantomData<T>);
12
13#[derive(Copy, Clone, Default)]
14pub struct Just<V: Value>(PhantomData<V>);
15
16impl<T: Type> Value for Nothing<T> {
17    type Type = Maybe<T>;
18}
19
20impl<T: Type, V: Value<Type=T>> Value for Just<V> {
21    type Type = Maybe<T>;
22}
23
24// is nothing
25#[derive(Copy, Clone, Default)]
26pub struct IsNoting<T: Type>(PhantomData<T>);
27
28impl<T: Type> Value for IsNoting<T> {
29    type Type = Lambda<Maybe<T>, Bool>;
30}
31
32impl<T: Type> App<Nothing<T>> for IsNoting<T> {
33    type Result = True;
34}
35
36impl<T: Type, V: Value<Type=T>> App<Just<V>> for IsNoting<T> {
37    type Result = False;
38}
39
40// flatten
41#[derive(Copy, Clone, Default)]
42pub struct Flatten<T: Type>(PhantomData<T>);
43
44impl<T: Type> Value for Flatten<T> {
45    type Type = Lambda<Maybe<Maybe<T>>, Maybe<T>>;
46}
47
48impl<T: Type> App<Nothing<Maybe<T>>> for Flatten<T> {
49    type Result = Nothing<T>;
50}
51
52impl<T: Type, I: Value<Type=Maybe<T>>> App<Just<I>> for Flatten<T> {
53    type Result = I;
54}
55
56#[derive(Copy, Clone, Default)]
57pub struct ToList<T: Type>(PhantomData<T>);
58
59impl<T: Type> Value for ToList<T> {
60    type Type = Lambda<Maybe<T>, List<T>>;
61}
62
63impl<T: Type> App<Nothing<T>> for ToList<T> {
64    type Result = Empty<T>;
65}
66
67impl<T: Type, V: Value<Type=T>> App<Just<V>> for ToList<T> {
68    type Result = Return<List<T>, V>;
69}
70
71// monad
72impl<T: Type> Monad for Maybe<T> {
73    type Wrapped = T;
74    type HKT<A: Type> = Maybe<A>;
75}
76
77impl<
78    T: Type,
79    V: Value<Type=T>
80> App<V> for Pure<Maybe<T>> {
81    type Result = Just<V>;
82}
83
84impl<A: Type, B: Type, F: Value<Type=Lambda<A, Maybe<B>>>> App<Nothing<A>> for BindOn<Maybe<A>, F> {
85    type Result = Nothing<B>;
86}
87
88impl<
89    A: Type,
90    B: Type,
91    F: Value<Type=Lambda<A, Maybe<B>>> + App<Ia, Result=R>,
92    Ia: Value<Type=A>,
93    R: Value<Type=Maybe<B>>
94> App<Just<Ia>> for BindOn<Maybe<A>, F> {
95    type Result = R;
96}
97
98// functor
99impl<T: Type> Functor<T> for Maybe<T> {
100    type HKT<A: Type> = Maybe<A>;
101}
102
103impl<A: Type, B: Type, F: Value<Type=Lambda<A, B>>> App<Nothing<A>> for MapOn<Maybe<A>, F> {
104    type Result = Nothing<B>;
105}
106
107impl<
108    A: Type,
109    B: Type,
110    F: Value<Type=Lambda<A, B>> + App<V, Result=R>,
111    V: Value<Type=A>,
112    R: Value<Type=B>
113> App<Just<V>> for MapOn<Maybe<A>, F> {
114    type Result = Just<R>;
115}
116
117