mirror of
https://github.com/IBM/fp-go.git
synced 2025-08-10 22:31:32 +02:00
initial checkin
Signed-off-by: Dr. Carsten Leue <carsten.leue@de.ibm.com>
This commit is contained in:
11
eq/contramap.go
Normal file
11
eq/contramap.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package eq
|
||||
|
||||
// Contramap implements an Equals predicate based on a mapping
|
||||
func Contramap[A, B any](f func(b B) A) func(Eq[A]) Eq[B] {
|
||||
return func(fa Eq[A]) Eq[B] {
|
||||
equals := fa.Equals
|
||||
return FromEquals(func(x, y B) bool {
|
||||
return equals(f(x), f(y))
|
||||
})
|
||||
}
|
||||
}
|
43
eq/eq.go
Normal file
43
eq/eq.go
Normal file
@@ -0,0 +1,43 @@
|
||||
package eq
|
||||
|
||||
import (
|
||||
F "github.com/ibm/fp-go/function"
|
||||
)
|
||||
|
||||
type Eq[T any] interface {
|
||||
Equals(x, y T) bool
|
||||
}
|
||||
|
||||
type eq[T any] struct {
|
||||
c func(x, y T) bool
|
||||
}
|
||||
|
||||
func (self eq[T]) Equals(x, y T) bool {
|
||||
return self.c(x, y)
|
||||
}
|
||||
|
||||
func strictEq[A comparable](a, b A) bool {
|
||||
return a == b
|
||||
}
|
||||
|
||||
// FromStrictEquals constructs an `Eq` from the canonical comparison function
|
||||
func FromStrictEquals[T comparable]() Eq[T] {
|
||||
return FromEquals(strictEq[T])
|
||||
}
|
||||
|
||||
// FromEquals constructs an `Eq` from the comparison function
|
||||
func FromEquals[T any](c func(x, y T) bool) Eq[T] {
|
||||
return eq[T]{c: c}
|
||||
}
|
||||
|
||||
// Empty returns the equals predicate that is always true
|
||||
func Empty[T any]() Eq[T] {
|
||||
return FromEquals(F.Constant2[T, T](true))
|
||||
}
|
||||
|
||||
// Equals returns a predicate to test if one value equals the other under an equals predicate
|
||||
func Equals[T any](eq Eq[T]) func(T) func(T) bool {
|
||||
return func(other T) func(T) bool {
|
||||
return F.Bind2nd(eq.Equals, other)
|
||||
}
|
||||
}
|
18
eq/monoid.go
Normal file
18
eq/monoid.go
Normal file
@@ -0,0 +1,18 @@
|
||||
package eq
|
||||
|
||||
import (
|
||||
M "github.com/ibm/fp-go/monoid"
|
||||
S "github.com/ibm/fp-go/semigroup"
|
||||
)
|
||||
|
||||
func Semigroup[A any]() S.Semigroup[Eq[A]] {
|
||||
return S.MakeSemigroup(func(x, y Eq[A]) Eq[A] {
|
||||
return FromEquals(func(a, b A) bool {
|
||||
return x.Equals(a, b) && y.Equals(a, b)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
func Monoid[A any]() M.Monoid[Eq[A]] {
|
||||
return M.MakeMonoid(Semigroup[A]().Concat, Empty[A]())
|
||||
}
|
13
eq/testing/eq.go
Normal file
13
eq/testing/eq.go
Normal file
@@ -0,0 +1,13 @@
|
||||
package testing
|
||||
|
||||
import (
|
||||
EQ "github.com/ibm/fp-go/eq"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
// Eq implements the equal operation based on `ObjectsAreEqualValues` from the assertion library
|
||||
func Eq[A any]() EQ.Eq[A] {
|
||||
return EQ.FromEquals(func(l, r A) bool {
|
||||
return assert.ObjectsAreEqualValues(l, r)
|
||||
})
|
||||
}
|
Reference in New Issue
Block a user