blob: 4ce4ba3f63cfa1ad405143f71dcada58b2cba69e [file] [log] [blame]
xinau41e30c62019-09-06 11:05:02 +00001// Copyright 2018 The CUE Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package list
16
17import (
18 "fmt"
19
20 "cuelang.org/go/internal"
21 "github.com/cockroachdb/apd/v2"
22)
23
24// Avg returns the average value of a non empty list xs.
25func Avg(xs []*internal.Decimal) (*internal.Decimal, error) {
26 if 0 == len(xs) {
27 return nil, fmt.Errorf("empty list")
28 }
29
30 s := apd.New(0, 0)
31 for _, x := range xs {
32 _, err := internal.BaseContext.Add(s, x, s)
33 if err != nil {
34 return nil, err
35 }
36 }
37
38 var d apd.Decimal
39 l := apd.New(int64(len(xs)), 0)
40 _, err := internal.BaseContext.Quo(&d, s, l)
41 if err != nil {
42 return nil, err
43 }
44 return &d, nil
45}
46
47// Max returns the maximum value of a non empty list xs.
48func Max(xs []*internal.Decimal) (*internal.Decimal, error) {
49 if 0 == len(xs) {
50 return nil, fmt.Errorf("empty list")
51 }
52
53 max := xs[0]
54 for _, x := range xs[1:] {
55 if -1 == max.Cmp(x) {
56 max = x
57 }
58 }
59 return max, nil
60}
61
62// Min returns the minimum value of a non empty list xs.
63func Min(xs []*internal.Decimal) (*internal.Decimal, error) {
64 if 0 == len(xs) {
65 return nil, fmt.Errorf("empty list")
66 }
67
68 min := xs[0]
69 for _, x := range xs[1:] {
70 if +1 == min.Cmp(x) {
71 min = x
72 }
73 }
74 return min, nil
75}
76
77// Product returns the product of a non empty list xs.
78func Product(xs []*internal.Decimal) (*internal.Decimal, error) {
79 d := apd.New(1, 0)
80 for _, x := range xs {
81 _, err := internal.BaseContext.Mul(d, x, d)
82 if err != nil {
83 return nil, err
84 }
85 }
86 return d, nil
87}
88
89// Sum returns the sum of a list non empty xs.
90func Sum(xs []*internal.Decimal) (*internal.Decimal, error) {
91 d := apd.New(0, 0)
92 for _, x := range xs {
93 _, err := internal.BaseContext.Add(d, x, d)
94 if err != nil {
95 return nil, err
96 }
97 }
98 return d, nil
99}