From 5a2c263a074daa0755a519ff93d2eb5bf4f9bee6 Mon Sep 17 00:00:00 2001 From: Xe Iaso Date: Mon, 15 Apr 2024 21:11:52 -0400 Subject: cursed: add reduce Signed-off-by: Xe Iaso --- cursed/reduce.go | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 cursed/reduce.go diff --git a/cursed/reduce.go b/cursed/reduce.go new file mode 100644 index 0000000..bd9f865 --- /dev/null +++ b/cursed/reduce.go @@ -0,0 +1,53 @@ +package cursed + +import "golang.org/x/exp/constraints" + +func Reduce[D any](data []D, doer func(D, D) D) D { + var initial D + + return Fold[D, D](initial, data, doer) +} + +func Fold[T any, U any](initial U, data []T, doer func(T, U) U) U { + acc := initial + for _, d := range data { + temp := doer(d, acc) + acc = temp + } + + return acc +} + +type Number interface { + constraints.Float | constraints.Integer +} + +func Sum[T Number](data []T) T { + return Reduce[T](data, func(x, y T) T { + return x + y + }) +} + +func Max[T Number](data []T) T { + return Reduce[T](data, func(x, y T) T { + if x > y { + return x + } else if y < x { + return y + } else { + return x // x == y + } + }) +} + +func Min[T Number](data []T) T { + return Reduce[T](data, func(x, y T) T { + if x > y { + return y + } else if y < x { + return x + } else { + return x // x == y + } + }) +} -- cgit v1.2.3