Skip to content

Commit

Permalink
Add Last
Browse files Browse the repository at this point in the history
  • Loading branch information
Primetalk committed Aug 22, 2022
1 parent a7af661 commit bba1f3d
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Expand Up @@ -326,6 +326,7 @@ After constructing the desired pipeline, the stream needs to be executed.
- `stream.AppendToSlice[A any](stm Stream[A], start []A) io.IO[[]A]`
- `stream.ToSlice[A any](stm Stream[A]) io.IO[[]A]`
- `stream.Head[A any](stm Stream[A]) io.IO[A]` - returns the first element if it exists. Otherwise - an error.
- `stream.Last[A any](stm Stream[A]) io.IO[A]` - Last keeps track of the current element of the stream and returns it when the stream completes.
- `stream.Collect[A any](stm Stream[A], collector func (A) error) io.IO[fun.Unit]` - collects all element from the stream and for each element invokes the provided function.
- `stream.ForEach[A any](stm Stream[A], collector func (A)) io.IO[fun.Unit]` - invokes a simple function for each element of the stream.
- `stream.Partition[A any, C any, D any](stm Stream[A], predicate func(A) bool, trueHandler func(Stream[A]) io.IO[C], falseHandler func(Stream[A]) io.IO[D]) io.IO[fun.Pair[C, D]]` - Partition divides the stream into two that are handled independently.
Expand Down
21 changes: 21 additions & 0 deletions stream/execution.go
Expand Up @@ -6,6 +6,7 @@ import (
"github.com/primetalk/goio/either"
"github.com/primetalk/goio/fun"
"github.com/primetalk/goio/io"
"github.com/primetalk/goio/option"
)

// Collector reads the stream and produces some value.
Expand Down Expand Up @@ -87,6 +88,26 @@ func Head[A any](stm Stream[A]) io.IO[A] {
})
}

// Last keeps track of the current element of the stream and returns it when the stream completes.
func Last[A any](stm Stream[A]) io.IO[A] {
return Head(
StateFlatMapWithFinish(
stm, option.None[A](),
func(a A, st option.Option[A]) io.IO[fun.Pair[option.Option[A], Stream[A]]] {
return io.Lift(fun.NewPair(option.Some(a), Empty[A]()))
},
func(st option.Option[A]) Stream[A] {
return option.Fold(st,
Lift[A],
func() Stream[A] {
return Fail[A](fmt.Errorf("last of an empty stream"))
},
)
},
),
)
}

// Partition divides the stream into two that are handled independently.
func Partition[A any, C any, D any](stm Stream[A],
predicate func(A) bool,
Expand Down
4 changes: 4 additions & 0 deletions stream/stream_test.go
Expand Up @@ -34,6 +34,10 @@ func TestGenerate(t *testing.T) {
res, err = io.UnsafeRunSync(stream.Head(powers2_10))
assert.NoError(t, err)
assert.Equal(t, 1024, res)

res, err = io.UnsafeRunSync(stream.Last(stream.Take(powers2, 10)))
assert.NoError(t, err)
assert.Equal(t, 1024, res)
}

func TestDrainAll(t *testing.T) {
Expand Down

0 comments on commit bba1f3d

Please sign in to comment.