-
Notifications
You must be signed in to change notification settings - Fork 1
/
s.go
74 lines (60 loc) · 1.51 KB
/
s.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package maybe
import "fmt"
// S implements the Maybe monad for a string. An S is considered 'valid' or
// 'invalid' depending on whether it contains a string or an error value.
type S struct {
just string
err error
}
// NewS constructs an S from a given string or error. If e is not nil, returns
// ErrS(e), otherwise returns JustS(s)
func NewS(s string, e error) S {
if e != nil {
return ErrS(e)
}
return JustS(s)
}
// JustS constructs a valid S from a given string.
func JustS(s string) S {
return S{just: s}
}
// ErrS constructs an invalid S from a given error.
func ErrS(e error) S {
return S{err: e}
}
// IsErr returns true for an invalid S.
func (m S) IsErr() bool {
return m.err != nil
}
// Bind applies a function that takes a string and returns an S.
func (m S) Bind(f func(s string) S) S {
if m.err != nil {
return m
}
return f(m.just)
}
// Split applies a function that takes a string and returns an AoS.
func (m S) Split(f func(s string) AoS) AoS {
if m.err != nil {
return ErrAoS(m.err)
}
return f(m.just)
}
// ToInt applies a function that takes a string and returns an I.
func (m S) ToInt(f func(s string) I) I {
if m.err != nil {
return ErrI(m.err)
}
return f(m.just)
}
// String returns a string representation, mostly useful for debugging.
func (m S) String() string {
if m.err != nil {
return fmt.Sprintf("Err %v", m.err)
}
return fmt.Sprintf("Just %v", m.just)
}
// Unbox returns the underlying string value or error.
func (m S) Unbox() (string, error) {
return m.just, m.err
}