@@ -17,13 +17,24 @@ func Some[A any](a A) Option[A] {
17
17
}
18
18
}
19
19
20
- // None trivially constructs an empty option
20
+ // None trivially constructs an empty option.
21
21
//
22
22
// None : Option[A].
23
23
func None [A any ]() Option [A ] {
24
24
return Option [A ]{}
25
25
}
26
26
27
+ // MaybeSome constructs an option from a pointer.
28
+ //
29
+ // MaybeSome : *A -> Option[A].
30
+ func MaybeSome [A any ](a * A ) Option [A ] {
31
+ if a == nil {
32
+ return None [A ]()
33
+ }
34
+
35
+ return Some [A ](* a )
36
+ }
37
+
27
38
// ElimOption is the universal Option eliminator. It can be used to safely
28
39
// handle all possible values inside the Option by supplying two continuations.
29
40
//
@@ -48,6 +59,33 @@ func (o Option[A]) UnwrapOr(a A) A {
48
59
return a
49
60
}
50
61
62
+ // UnwrapPtr is used to extract a reference to a value from an option, and we
63
+ // supply an empty pointer in the case when the Option is empty.
64
+ func (o Option [A ]) UnwrapToPtr () * A {
65
+ var v * A
66
+ o .WhenSome (func (a A ) {
67
+ v = & a
68
+ })
69
+
70
+ return v
71
+ }
72
+
73
+ // UnwrapOrFunc is used to extract a value from an option, and we supply a
74
+ // thunk to be evaluated in the case when the Option is empty.
75
+ func (o Option [A ]) UnwrapOrFunc (f func () A ) A {
76
+ return ElimOption (o , f , func (a A ) A { return a })
77
+ }
78
+
79
+ // UnwrapOrFuncErr is used to extract a value from an option, and we supply a
80
+ // thunk to be evaluated in the case when the Option is empty.
81
+ func (o Option [A ]) UnwrapOrFuncErr (f func () (A , error )) (A , error ) {
82
+ if o .isSome {
83
+ return o .some , nil
84
+ }
85
+
86
+ return f ()
87
+ }
88
+
51
89
// WhenSome is used to conditionally perform a side-effecting function that
52
90
// accepts a value of the type that parameterizes the option. If this function
53
91
// performs no side effects, WhenSome is useless.
@@ -117,6 +155,19 @@ func MapOption[A, B any](f func(A) B) func(Option[A]) Option[B] {
117
155
}
118
156
}
119
157
158
+ // MapOptionZ transforms a pure function A -> B into one that will operate
159
+ // inside the Option context. Unlike MapOption, this function will return the
160
+ // default/zero argument of the return type if the Option is empty.
161
+ func MapOptionZ [A , B any ](o Option [A ], f func (A ) B ) B {
162
+ var zero B
163
+
164
+ if o .IsNone () {
165
+ return zero
166
+ }
167
+
168
+ return f (o .some )
169
+ }
170
+
120
171
// LiftA2Option transforms a pure function (A, B) -> C into one that will
121
172
// operate in an Option context. For the returned function, if either of its
122
173
// arguments are None, then the result will be None.
0 commit comments