haskell_bits/impls/
option.rs1use crate::*;
2
3pub struct TypeCon;
4
5impl<T> TypeAppParam for Option<T> {
6 type Param = T;
7}
8
9impl<T> TypeApp<TypeCon, T> for Option<T> {}
10
11impl<T> WithTypeArg<T> for TypeCon {
12 type Type = Option<T>;
13}
14
15impl Functor for TypeCon {
16 fn fmap<TIn, TOut, F>(
17 f: F,
18 x: &<TypeCon as WithTypeArg<TIn>>::Type,
19 ) -> <TypeCon as WithTypeArg<TOut>>::Type
20 where
21 F: Fn(&TIn) -> TOut,
22 {
23 Option::map(x.as_ref(), f)
24 }
25}
26
27impl LinearFunctor for TypeCon {
28 fn lmap<TIn, TOut, F>(
29 f: F,
30 x: <TypeCon as WithTypeArg<TIn>>::Type,
31 ) -> <TypeCon as WithTypeArg<TOut>>::Type
32 where
33 F: Fn(TIn) -> TOut,
34 {
35 Option::map(x, f)
36 }
37}
38
39impl Lift for TypeCon {
40 fn lift<T>(x: T) -> <TypeCon as WithTypeArg<T>>::Type {
41 From::from(x)
42 }
43}
44
45impl Applicative for TypeCon {
46 fn ap<TIn, TOut, TFunc>(
47 f: &<TypeCon as WithTypeArg<TFunc>>::Type,
48 x: &<TypeCon as WithTypeArg<TIn>>::Type,
49 ) -> <TypeCon as WithTypeArg<TOut>>::Type
50 where
51 TFunc: Fn(&TIn) -> TOut,
52 {
53 f.as_ref().and_then(|f_val| fmap(f_val, x))
54 }
55
56 fn lift2<TIn1, TIn2, TOut, TFunc>(
57 f: TFunc,
58 x1: &<TypeCon as WithTypeArg<TIn1>>::Type,
59 x2: &<TypeCon as WithTypeArg<TIn2>>::Type,
60 ) -> <TypeCon as WithTypeArg<TOut>>::Type
61 where
62 TFunc: Fn(&TIn1, &TIn2) -> TOut,
63 {
64 x1.as_ref()
65 .and_then(|x1_val| x2.as_ref().map(|x2_val| f(x1_val, x2_val)))
66 }
67}
68
69impl LinearApplicative for TypeCon {
70 fn lap<TIn, TOut, TFunc>(
71 f: <TypeCon as WithTypeArg<TFunc>>::Type,
72 x: <TypeCon as WithTypeArg<TIn>>::Type,
73 ) -> <TypeCon as WithTypeArg<TOut>>::Type
74 where
75 TFunc: FnOnce(TIn) -> TOut,
76 {
77 f.and_then(|f_val| x.map(|x_val| f_val(x_val)))
78 }
79
80 fn llift2<TIn1, TIn2, TOut, TFunc>(
81 f: TFunc,
82 x1: <TypeCon as WithTypeArg<TIn1>>::Type,
83 x2: <TypeCon as WithTypeArg<TIn2>>::Type,
84 ) -> <TypeCon as WithTypeArg<TOut>>::Type
85 where
86 TFunc: FnOnce(TIn1, TIn2) -> TOut,
87 {
88 x1.and_then(|x1val| x2.map(|x2val| f(x1val, x2val)))
89 }
90}
91
92impl Monad for TypeCon {
93 fn bind<TIn, TOut, F>(
94 x: &<TypeCon as WithTypeArg<TIn>>::Type,
95 f: F,
96 ) -> <TypeCon as WithTypeArg<TOut>>::Type
97 where
98 F: Fn(&TIn) -> <TypeCon as WithTypeArg<TOut>>::Type,
99 {
100 x.as_ref().and_then(f)
101 }
102}
103
104impl LinearMonad for TypeCon {
105 fn lbind<TIn, TOut, F>(
106 x: <TypeCon as WithTypeArg<TIn>>::Type,
107 f: F,
108 ) -> <TypeCon as WithTypeArg<TOut>>::Type
109 where
110 F: FnOnce(TIn) -> <TypeCon as WithTypeArg<TOut>>::Type,
111 {
112 x.and_then(f)
113 }
114}