-
-
Notifications
You must be signed in to change notification settings - Fork 87
/
state.go
52 lines (45 loc) · 1.02 KB
/
state.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
package mo
func NewState[S any, A any](f func(state S) (A, S)) State[S, A] {
return State[S, A]{
run: f,
}
}
func ReturnState[S any, A any](x A) State[S, A] {
return State[S, A]{
run: func(state S) (A, S) {
return x, state
},
}
}
// State represents a function `(S) -> (A, S)`, where `S` is state, `A` is result.
type State[S any, A any] struct {
run func(state S) (A, S)
}
// Run executes a computation in the State monad.
func (s State[S, A]) Run(state S) (A, S) {
return s.run(state)
}
// Get returns the current state.
func (s State[S, A]) Get() State[S, S] {
return State[S, S]{
run: func(state S) (S, S) {
return state, state
},
}
}
// Modify the state by applying a function to the current state.
func (s State[S, A]) Modify(f func(state S) S) State[S, A] {
return State[S, A]{
run: func(state S) (A, S) {
return empty[A](), f(state)
},
}
}
// Put set the state.
func (s State[S, A]) Put(state S) State[S, A] {
return State[S, A]{
run: func(state S) (A, S) {
return empty[A](), state
},
}
}