mirror of
https://github.com/IBM/fp-go.git
synced 2025-06-19 00:17:48 +02:00
initial checkin
Signed-off-by: Dr. Carsten Leue <carsten.leue@de.ibm.com>
This commit is contained in:
43
array/monoid.go
Normal file
43
array/monoid.go
Normal file
@ -0,0 +1,43 @@
|
||||
package array
|
||||
|
||||
import (
|
||||
"github.com/ibm/fp-go/internal/array"
|
||||
M "github.com/ibm/fp-go/monoid"
|
||||
)
|
||||
|
||||
func concat[T any](left, right []T) []T {
|
||||
// some performance checks
|
||||
ll := len(left)
|
||||
lr := len(right)
|
||||
if ll == 0 {
|
||||
return right
|
||||
}
|
||||
if lr == 0 {
|
||||
return left
|
||||
}
|
||||
// need to copy
|
||||
buf := make([]T, ll+lr)
|
||||
copy(buf[copy(buf, left):], right)
|
||||
return buf
|
||||
}
|
||||
|
||||
func Monoid[T any]() M.Monoid[[]T] {
|
||||
return M.MakeMonoid(concat[T], Empty[T]())
|
||||
}
|
||||
|
||||
func addLen[A any](count int, data []A) int {
|
||||
return count + len(data)
|
||||
}
|
||||
|
||||
// ConcatAll efficiently concatenates the input arrays into a final array
|
||||
func ArrayConcatAll[A any](data ...[]A) []A {
|
||||
// get the full size
|
||||
count := array.Reduce(data, addLen[A], 0)
|
||||
buf := make([]A, count)
|
||||
// copy
|
||||
array.Reduce(data, func(idx int, seg []A) int {
|
||||
return idx + copy(buf[idx:], seg)
|
||||
}, 0)
|
||||
// returns the final array
|
||||
return buf
|
||||
}
|
Reference in New Issue
Block a user