ehh i dunno

master
Jordan Orelli 3 years ago
parent e8710f676d
commit 09274b41d4

@ -44,14 +44,16 @@ func strip[X any](f func(X) error) func(interface{}) error {
} }
} }
func stripReturn[X any](f func() X) func() interface{} {
return func() interface {} { return f() }
}
// Box takes a mergeable value and creates a new mergeable value of type Boxed. // Box takes a mergeable value and creates a new mergeable value of type Boxed.
// Any two Boxed values can attempt to merge at runtime. // Any two Boxed values can attempt to merge at runtime.
func Box[X Merges[X]](x X) Boxed { func Box[X Merges[X]](x X) Boxed {
return Boxed{ return Boxed{
val: x, val: x,
ident: func() interface{} { ident: stripReturn(x.MergeIdentity),
return x.MergeIdentity()
},
merge: strip(x.Merge), merge: strip(x.Merge),
} }
} }

@ -18,6 +18,7 @@ package merge
// Although the type B satisfies the interface Merges[*C], it does not satisfy // Although the type B satisfies the interface Merges[*C], it does not satisfy
// the constraint [X Merges[X]], which is what is used throughout this package. // the constraint [X Merges[X]], which is what is used throughout this package.
type Merges[X any] interface { type Merges[X any] interface {
// MergeIdentity defines the identity for the merge function
MergeIdentity() X MergeIdentity() X
Merge(X) error Merge(X) error
} }

@ -10,15 +10,13 @@ type additive struct {
total int total int
} }
func (*additive) MergeIdentity() *additive {
return new(additive)
}
func (a *additive) Merge(b *additive) error { func (a *additive) Merge(b *additive) error {
a.total += b.total a.total += b.total
return nil return nil
} }
func (*additive) MergeIdentity() *additive { return new(additive) }
func add(n int) *additive { func add(n int) *additive {
return &additive{total: n} return &additive{total: n}
} }
@ -27,9 +25,7 @@ type multiplicative struct {
scale int scale int
} }
func (m *multiplicative) MergeIdentity() *multiplicative { func (*multiplicative) MergeIdentity() *multiplicative { return &multiplicative{scale: 1} }
return &multiplicative{scale: 1}
}
func (m *multiplicative) Merge(v *multiplicative) error { func (m *multiplicative) Merge(v *multiplicative) error {
m.scale *= v.scale m.scale *= v.scale
@ -46,14 +42,14 @@ type exclusive struct {
stock int stock int
} }
func (*exclusive) MergeIdentity() *exclusive { return new(exclusive) }
func (e *exclusive) Merge(source *exclusive) error { func (e *exclusive) Merge(source *exclusive) error {
e.stock += source.stock e.stock += source.stock
source.stock = 0 source.stock = 0
return nil return nil
} }
func (*exclusive) MergeIdentity() *exclusive { return new(exclusive) }
func ex(n int) *exclusive { func ex(n int) *exclusive {
return &exclusive{stock: n} return &exclusive{stock: n}
} }

Loading…
Cancel
Save