github.com/MontFerret/ferret@v0.18.0/pkg/stdlib/math/mean.go (about)

     1  package math
     2  
     3  import (
     4  	"math"
     5  
     6  	"github.com/MontFerret/ferret/pkg/runtime/core"
     7  	"github.com/MontFerret/ferret/pkg/runtime/values"
     8  	"github.com/MontFerret/ferret/pkg/runtime/values/types"
     9  )
    10  
    11  func mean(input *values.Array) (values.Float, error) {
    12  	if input.Length() == 0 {
    13  		return values.NewFloat(math.NaN()), nil
    14  	}
    15  
    16  	var err error
    17  	var sum float64
    18  
    19  	input.ForEach(func(value core.Value, idx int) bool {
    20  		err = core.ValidateType(value, types.Int, types.Float)
    21  
    22  		if err != nil {
    23  			return false
    24  		}
    25  
    26  		sum += toFloat(value)
    27  
    28  		return true
    29  	})
    30  
    31  	if err != nil {
    32  		return 0, err
    33  	}
    34  
    35  	return values.NewFloat(sum / float64(input.Length())), nil
    36  }