From b6efa35b03639989586fcd7a0c1a765fb402562f Mon Sep 17 00:00:00 2001 From: Carsten Leue Date: Wed, 29 Nov 2023 22:13:46 +0100 Subject: [PATCH] fix: bug in compact array (#87) Signed-off-by: Dr. Carsten Leue --- either/array.go | 6 +++--- either/array_test.go | 18 ++++++++++++++++++ option/array.go | 2 +- option/array_test.go | 11 +++++++++++ 4 files changed, 33 insertions(+), 4 deletions(-) create mode 100644 either/array_test.go diff --git a/either/array.go b/either/array.go index f3151dd..c7326aa 100644 --- a/either/array.go +++ b/either/array.go @@ -61,14 +61,14 @@ func SequenceArray[E, A any](ma []Either[E, A]) Either[E, []A] { return SequenceArrayG[[]A](ma) } -// CompactArrayG discards the none values and keeps the some values +// CompactArrayG discards the none values and keeps the right values func CompactArrayG[A1 ~[]Either[E, A], A2 ~[]A, E, A any](fa A1) A2 { return RA.Reduce(fa, func(out A2, value Either[E, A]) A2 { return MonadFold(value, F.Constant1[E](out), F.Bind1st(RA.Append[A2, A], out)) - }, make(A2, len(fa))) + }, make(A2, 0, len(fa))) } -// CompactArray discards the none values and keeps the some values +// CompactArray discards the none values and keeps the right values func CompactArray[E, A any](fa []Either[E, A]) []A { return CompactArrayG[[]Either[E, A], []A](fa) } diff --git a/either/array_test.go b/either/array_test.go new file mode 100644 index 0000000..523c1b9 --- /dev/null +++ b/either/array_test.go @@ -0,0 +1,18 @@ +package either + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestCompactArray(t *testing.T) { + ar := []Either[string, string]{ + Of[string]("ok"), + Left[string]("err"), + Of[string]("ok"), + } + + res := CompactArray(ar) + assert.Equal(t, 2, len(res)) +} diff --git a/option/array.go b/option/array.go index 2fd02b1..25050ee 100644 --- a/option/array.go +++ b/option/array.go @@ -65,7 +65,7 @@ func SequenceArray[A any](ma []Option[A]) Option[[]A] { func CompactArrayG[A1 ~[]Option[A], A2 ~[]A, A any](fa A1) A2 { return RA.Reduce(fa, func(out A2, value Option[A]) A2 { return MonadFold(value, F.Constant(out), F.Bind1st(RA.Append[A2, A], out)) - }, make(A2, len(fa))) + }, make(A2, 0, len(fa))) } // CompactArray discards the none values and keeps the some values diff --git a/option/array_test.go b/option/array_test.go index a4c67bb..2a31baa 100644 --- a/option/array_test.go +++ b/option/array_test.go @@ -34,3 +34,14 @@ func TestSequenceArray(t *testing.T) { assert.Equal(t, res, Of([]int{1, 2})) } + +func TestCompactArray(t *testing.T) { + ar := []Option[string]{ + Of("ok"), + None[string](), + Of("ok"), + } + + res := CompactArray(ar) + assert.Equal(t, 2, len(res)) +}