57 lines
1.0 KiB
Go
57 lines
1.0 KiB
Go
|
package parallel
|
||
|
|
||
|
import (
|
||
|
"sync"
|
||
|
|
||
|
"git.tuxpa.in/a/lambda"
|
||
|
)
|
||
|
|
||
|
var routineCount int = 1
|
||
|
|
||
|
func SetRoutineCount(n int) {
|
||
|
routineCount = n
|
||
|
}
|
||
|
|
||
|
func Map[T any](xs []T, fx func(T) T) []T {
|
||
|
spl := lambda.Split(xs, routineCount)
|
||
|
wg := new(sync.WaitGroup)
|
||
|
wg.Add(len(spl))
|
||
|
for i, v := range spl {
|
||
|
go func(ix int, vx []T) {
|
||
|
spl[ix] = lambda.Map(vx, fx)
|
||
|
wg.Done()
|
||
|
}(i, v)
|
||
|
}
|
||
|
wg.Wait()
|
||
|
return lambda.Flatten(spl)
|
||
|
}
|
||
|
func Foldl[T any](xs []T, fx func(T, T) T) T {
|
||
|
spl := lambda.Split(xs, routineCount)
|
||
|
wg := new(sync.WaitGroup)
|
||
|
wg.Add(len(spl))
|
||
|
tmp := make([]T, len(spl))
|
||
|
for i, v := range spl {
|
||
|
go func(ix int, vx []T) {
|
||
|
tmp[ix] = lambda.Foldl(vx, fx)
|
||
|
wg.Done()
|
||
|
}(i, v)
|
||
|
}
|
||
|
wg.Wait()
|
||
|
return lambda.Foldl(tmp, fx)
|
||
|
}
|
||
|
|
||
|
func Foldr[T any](xs []T, fx func(T, T) T) T {
|
||
|
spl := lambda.Split(xs, routineCount)
|
||
|
wg := new(sync.WaitGroup)
|
||
|
wg.Add(len(spl))
|
||
|
tmp := make([]T, len(spl))
|
||
|
for i, v := range spl {
|
||
|
go func(ix int, vx []T) {
|
||
|
tmp[ix] = lambda.Foldr(vx, fx)
|
||
|
wg.Done()
|
||
|
}(i, v)
|
||
|
}
|
||
|
wg.Wait()
|
||
|
return lambda.Foldr(tmp, fx)
|
||
|
}
|