Skip to content

Commit

Permalink
add examples for State[S, A]
Browse files Browse the repository at this point in the history
  • Loading branch information
OlegStotsky committed May 8, 2022
1 parent 1bb0416 commit f7f6132
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 9 deletions.
21 changes: 13 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,18 +141,23 @@ Represent function func (S) (A, S), where S is state, A is result

### Create State
```go
x := state.Return(int, string)(5)
y := state.Put(int)(5)
x := state.Return[any, int](5)
y := state.Put(100)
fmt.Println(x.RunState(nil)) // prints 5
fmt.Println(y.RunState(6)) // prints 100
```

### Transform State into new value
```go
func CountZeroes(numbs []int) int {
counter := state.Put(int)(0)
for _, x := range numbs {
state := state.bindI(int, Unit, int)(counter, state.Get(int)())
counter = state.FlatMap(int, int, int)(state, func(c int) { return state.Put(int)(c + 1) })
func CountZeroes(ints []int) int {
counter := state.Put[int](0)
for _, x := range ints {
if x == 0 {
s := state.BindI[int, util.Unit, int](counter, state.Get[int]())
counter = state.FlatMap[int, int, util.Unit](s, func(c int) state.State[int, util.Unit] { return state.Put[int](c + 1) })
}
}
return counter.RunState(0)
_, s := counter.RunState(0)
return s
}
```
28 changes: 28 additions & 0 deletions cmd/examples/state/state.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package main

import (
"fmt"
"github.com/OlegStotsky/go-monads/state"
"github.com/OlegStotsky/go-monads/util"
)

func CountZeroes(ints []int) int {
counter := state.Put[int](0)
for _, x := range ints {
if x == 0 {
s := state.BindI[int, util.Unit, int](counter, state.Get[int]())
counter = state.FlatMap[int, int, util.Unit](s, func(c int) state.State[int, util.Unit] { return state.Put[int](c + 1) })
}
}
_, s := counter.RunState(0)
return s
}

func main() {
x := state.Return[any, int](5)
y := state.Put(100)
fmt.Println(x.RunState(nil)) // prints 5
fmt.Println(y.RunState(6)) // prints 100

fmt.Println(CountZeroes([]int{5, 4, 0, 0, 1, 0})) // prints 3
}
2 changes: 1 addition & 1 deletion state/state.go2 → state/state.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ func Put[S any](newState S) State[S, util.Unit] {
}

//Analogue of flatMap with ignoring value of base State
func bindI[S, A, B any](s State[S, A], s2 State[S, B]) State[S, B] {
func BindI[S, A, B any](s State[S, A], s2 State[S, B]) State[S, B] {
return stateImpl[S, B]{f: func(state S) (B, S) {
_, newState := s.RunState(state)
return s2.RunState(newState)
Expand Down

0 comments on commit f7f6132

Please sign in to comment.