sliceutil

package
v1.154.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 3, 2026 License: MIT Imports: 4 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package sliceutil provides generic, allocation-conscious helpers for common slice operations and numeric dataset summarization.

What It Provides

Functional slice primitives, generic over `S ~[]E`, whose callbacks receive the element index:

  • 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, and returns ErrEmptySlice for an empty slice.
  • DescStats includes count, sum, min/max (+ indexes), range, mode, mean/median, entropy, variance, standard deviation, skewness, and excess kurtosis.

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

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrEmptySlice = errors.New("input slice is empty")

ErrEmptySlice is returned by Stats when the input slice contains no elements.

Functions

func Filter

func Filter[S ~[]E, E any](s S, f func(int, E) bool) S

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

func Map[S ~[]E, E any, U any](s S, f func(int, E) U) []U

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

func Reduce[S ~[]E, E any, U any](s S, init U, f func(int, E, U) U) U

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

func Stats[S ~[]V, V typeutil.Number](s S) (*DescStats[V], error)

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

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL