-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththen.go
44 lines (42 loc) · 1.1 KB
/
then.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package opt
// Then applies the function ‘fn’ to the value inside of the optional-type ‘op’, if the optional-type ‘op’ is holding something, and returns the resulting optional-type.
// If the optional-type ‘op’ is holding nothing, then Then also returns nothing.
//
// For example:
//
// fn := func(s string) opt.Optional[byte] {
//
// if len(s) < 2 {
// return opt.Nothing[byte]()
// }
//
// return opt.Something[byte](s[1])
// }
//
// var op opt.Optional[string] = opt.Something("Hello world!"")
//
// var result opt.Optional[byte] = opt.Then(op, fn)
//
// // result == opt.Something[byte]('e')
//
// // ...
//
// var op2 opt.Optional[string] = opt.Something[string]("X")
//
// var result2 opt.Optional[byte] = opt.Then(op, fn)
//
// // result2 == opt.Nothing[byte]()
//
// // ...
//
// var op2 opt.Optional[string] = opt.Nothing[string]()
//
// var result2 opt.Optional[byte] = opt.Then(op, fn)
//
// // result2 == opt.Nothing[byte]()
func Then[T1 any, T2 any](op Optional[T1], fn func(T1)Optional[T2]) Optional[T2] {
if op.IsNothing() {
return Nothing[T2]()
}
return fn(op.value)
}