github.com/isyscore/isc-gobase@v1.5.3-0.20231218061332-cbc7451899e9/isc/reduce.go (about)

     1  package isc
     2  
     3  /// functions for list
     4  
     5  func Reduce[S any, T any](list []T, init func(T) S, f func(S, T) S) S {
     6  	accumulator := init(list[0])
     7  	for _, e := range list[1:] {
     8  		accumulator = f(accumulator, e)
     9  	}
    10  	return accumulator
    11  }
    12  
    13  func ReduceIndexed[S any, T any](list []T, init func(int, T) S, f func(int, S, T) S) S {
    14  	accumulator := init(0, list[0])
    15  	for i, e := range list[1:] {
    16  		accumulator = f(i, accumulator, e)
    17  	}
    18  	return accumulator
    19  }