Documentation
¶
Overview ¶
Package sliceutil provides generic, allocation-conscious helpers for common slice operations and numeric dataset summarization.
Problem ¶
Go intentionally keeps slice operations minimal in the standard library. Teams typically re-implement the same small helpers for filter/map/reduce in multiple packages, and statistical summary code is often copied with subtle differences. This package centralizes those patterns into a reusable, type-safe API.
What It Provides ¶
Functional slice primitives:
- Filter: returns a new slice containing elements that satisfy a predicate.
- Map: returns a new slice with each element transformed to a new type.
- Reduce: folds a slice into a single value using an accumulator.
Descriptive statistics for numeric slices:
- Stats: computes a DescStats summary for any numeric slice type.
- DescStats includes count, sum, min/max (+ indexes), range, mode, mean/median, entropy, variance, standard deviation, skewness, and excess kurtosis.
Key Features ¶
- Generic APIs (`S ~[]E`) that work with native and named slice types.
- Functional helpers include element index in callbacks for context-aware transforms.
- Numeric statistics are available for all typeutil.Number types.
- Safe error behavior for invalid input: Stats returns ErrEmptySlice for empty slices.
- Clear composition model: use Filter, Map, and Reduce in pipelines, then summarize results with Stats.
Usage ¶
adults := sliceutil.Filter(users, func(_ int, u User) bool { return u.Age >= 18 })
names := sliceutil.Map(adults, func(_ int, u User) string { return u.Name })
total := sliceutil.Reduce([]int{1, 2, 3, 4}, 0, func(_ int, v int, acc int) int {
return acc + v
})
_ = names
_ = total
ds, err := sliceutil.Stats([]int{53, 83, 13, 79})
if err != nil {
return err
}
_ = ds.Mean
This package is ideal for Go services and libraries that want concise, predictable slice transformations and lightweight statistical summaries without pulling in heavy data-processing dependencies.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrEmptySlice = errors.New("input slice is empty")
ErrEmptySlice is returned by Stats when the input slice contains no elements.
Functions ¶
func Filter ¶
Filter returns a new slice containing only elements for which f returns true.
Example ¶
package main
import (
"fmt"
"github.com/tecnickcom/nurago/pkg/sliceutil"
)
func main() {
s := []string{"Hello", "World", "Extra"}
filterFn := func(_ int, v string) bool { return v == "World" }
s2 := sliceutil.Filter(s, filterFn)
fmt.Println(s2)
}
Output: [World]
func Map ¶
Map returns a new slice containing f applied to each element of s.
Example ¶
package main
import (
"fmt"
"github.com/tecnickcom/nurago/pkg/sliceutil"
)
func main() {
s := []string{"Hello", "World", "Extra"}
mapFn := func(k int, v string) int { return k + len(v) }
s2 := sliceutil.Map(s, mapFn)
fmt.Println(s2)
}
Output: [5 6 7]
func Reduce ¶
Reduce folds s into one value by repeatedly applying f to each element and accumulator state.
Example ¶
package main
import (
"fmt"
"github.com/tecnickcom/nurago/pkg/sliceutil"
)
func main() {
s := []int{2, 3, 5, 7, 11}
init := 97
reduceFn := func(k, v, r int) int { return k + v + r }
r := sliceutil.Reduce(s, init, reduceFn)
fmt.Println(r)
}
Output: 135
Types ¶
type DescStats ¶
type DescStats[V typeutil.Number] struct { // Count is the total number of items in the data set. Count int `json:"count"` // Entropy is the entropy of the value distribution, expressed in nats // (natural logarithm, base e); divide by ln(2) to convert to bits. // It is meaningful only for non-negative data with a positive sum, where the // values can be interpreted as an unnormalized probability distribution. // For data whose sum is not strictly positive (e.g. signed data, all zeros, // or a zero/negative total) the entropy is reported as 0 to avoid NaN/Inf; // individual non-positive values are skipped for the same reason. Entropy float64 `json:"entropy"` // ExKurtosis is the sample excess kurtosis (G2) of the data set: the // bias-corrected fourth standardized moment with 3.0 subtracted, so that the // excess kurtosis of a normal distribution is zero. // It is defined only for n >= 4 with a non-zero standard deviation; otherwise // it is reported as 0. ExKurtosis float64 `json:"exkurtosis"` // Max is the maximum value of the data. Max V `json:"max"` // MaxID is the index (key) of the Max malue in a data set. MaxID int `json:"maxid"` // Mean or Average is a central tendency of the data. Mean float64 `json:"mean"` // MeanDev is the Mean Absolute Deviation: the average of the absolute // differences between each value and Mean, normalized by n (unlike the // sample Variance, which divides by n-1). MeanDev float64 `json:"meandev"` // Median is the value that divides the data into 2 equal parts. // When the data is sorted, the number of terms on the left and right side of median is the same. Median float64 `json:"median"` // Min is the minimal value of the data. Min V `json:"min"` // MinID is the index (key) of the Min malue in a data set. MinID int `json:"minid"` // Mode is the value with the highest frequency in the data set. Ties are // broken deterministically by choosing the smallest tied value. // When ModeFreq == 1 no value repeats and there is no true mode; Mode is // then the smallest value in the data set. Mode V `json:"mode"` // ModeFreq is the frequency of the Mode value. A value of 1 means no value // repeats in the data set (see Mode). ModeFreq int `json:"modefreq"` // Range is the difference between the highest (Max) and lowest (Min) value, // using the element type V. As with Sum, this can overflow for narrow signed // integer element types with extreme values. Range V `json:"range"` // Skewness measures the asymmetry of the distribution about its mean, as the // adjusted Fisher-Pearson standardized moment coefficient (sample G1). // It is defined only for n >= 3 with a non-zero standard deviation; otherwise // it is reported as 0. Skewness float64 `json:"skewness"` // StdDev is the sample standard deviation: the square root of the sample // Variance (which uses the n-1 divisor). StdDev float64 `json:"stddev"` // Sum is the total of all values, using the element type V. For narrow // integer element types or very large data sets it can overflow; use a wide // element type (int64/float64) when exact large totals are required. Sum V `json:"sum"` // Variance is the sample variance: the sum of squared deviations from Mean // divided by n-1 (Bessel's correction). It is 0 for a single element, where // the sample variance is undefined. Variance float64 `json:"variance"` }
DescStats contains descriptive statistics items for a data set.
func Stats ¶
Stats computes a DescStats summary for a numeric slice including count, sum, min/max, range, mode, mean, median, and shape metrics. It returns ErrEmptySlice if s has no elements.
Example ¶
package main
import (
"fmt"
"log"
"github.com/tecnickcom/nurago/pkg/sliceutil"
)
func main() {
data := []int{53, 83, 13, 79, 13, 37, 83, 29, 37, 13, 83, 83}
ds, err := sliceutil.Stats(data)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Count: %d\n", ds.Count)
fmt.Printf("Entropy: %.3f\n", ds.Entropy)
fmt.Printf("ExKurtosis: %.3f\n", ds.ExKurtosis)
fmt.Printf("Max: %d\n", ds.Max)
fmt.Printf("MaxID: %d\n", ds.MaxID)
fmt.Printf("Mean: %.3f\n", ds.Mean)
fmt.Printf("MeanDev: %.3f\n", ds.MeanDev)
fmt.Printf("Median: %.3f\n", ds.Median)
fmt.Printf("Min: %d\n", ds.Min)
fmt.Printf("MinID: %d\n", ds.MinID)
fmt.Printf("Mode: %d\n", ds.Mode)
fmt.Printf("ModeFreq: %d\n", ds.ModeFreq)
fmt.Printf("Range: %d\n", ds.Range)
fmt.Printf("Skewness: %.3f\n", ds.Skewness)
fmt.Printf("StdDev: %.3f\n", ds.StdDev)
fmt.Printf("Sum: %d\n", ds.Sum)
fmt.Printf("Variance: %.3f\n", ds.Variance)
}
Output: Count: 12 Entropy: 2.302 ExKurtosis: -1.910 Max: 83 MaxID: 1 Mean: 50.500 MeanDev: 26.833 Median: 45.000 Min: 13 MinID: 2 Mode: 83 ModeFreq: 4 Range: 70 Skewness: -0.049 StdDev: 30.285 Sum: 606 Variance: 917.182