1
0
mirror of https://github.com/IBM/fp-go.git synced 2025-08-10 22:31:32 +02:00

fix: use endomorphism

Signed-off-by: Dr. Carsten Leue <carsten.leue@de.ibm.com>
This commit is contained in:
Dr. Carsten Leue
2023-12-17 12:34:15 +01:00
parent 5caabf478c
commit 5fcd0b1595
9 changed files with 133 additions and 17 deletions

View File

@@ -531,3 +531,12 @@ func MonadFlap[GFAB ~map[K]func(A) B, GB ~map[K]B, K comparable, A, B any](fab G
func Flap[GFAB ~map[K]func(A) B, GB ~map[K]B, K comparable, A, B any](a A) func(GFAB) GB {
return FC.Flap(MonadMap[GFAB, GB], a)
}
func Copy[M ~map[K]V, K comparable, V any](m M) M {
return duplicate(m)
}
func Clone[M ~map[K]V, K comparable, V any](f func(V) V) func(m M) M {
// impementation assumes that map does not optimize for the empty map
return Map[M, M](f)
}

View File

@@ -284,3 +284,13 @@ func MonadFlap[B any, K comparable, A any](fab map[K]func(A) B, a A) map[K]B {
func Flap[B any, K comparable, A any](a A) func(map[K]func(A) B) map[K]B {
return G.Flap[map[K]func(A) B, map[K]B](a)
}
// Copy creates a shallow copy of the map
func Copy[K comparable, V any](m map[K]V) map[K]V {
return G.Copy[map[K]V](m)
}
// Clone creates a deep copy of the map using the provided endomorphism to clone the values
func Clone[K comparable, V any](f func(V) V) func(m map[K]V) map[K]V {
return G.Clone[map[K]V](f)
}

View File

@@ -21,6 +21,7 @@ import (
"strings"
"testing"
A "github.com/IBM/fp-go/array"
"github.com/IBM/fp-go/internal/utils"
O "github.com/IBM/fp-go/option"
S "github.com/IBM/fp-go/string"
@@ -131,3 +132,20 @@ func ExampleValuesOrd() {
// Output: [c b a]
}
func TestCopyVsClone(t *testing.T) {
slc := []string{"b", "c"}
src := map[string][]string{
"a": slc,
}
// make a shallow copy
cpy := Copy(src)
// make a deep copy
cln := Clone[string](A.Copy[string])(src)
assert.Equal(t, cpy, cln)
// make a modification to the original slice
slc[0] = "d"
assert.NotEqual(t, cpy, cln)
assert.Equal(t, src, cpy)
}